randrange in python | randrange vs randint

In this tutorial, we will discuss the randrange function in python.

The randrange() function

Python random module contains all the random number generation functions. Thus, to use randrange function we should import random module.

The randrange function returns an element from a range of numbers.

Syntax

random.randrange(start, stop, step)

Parameters

  • start – An integer specifying at which position to start (optional) | default = 0
  • stop – An integer specifying end position (required)
  • step – An integer specifying the incrementation (optional) | default = 1

This function equivalent to random.choice(range(start,stop,step)). However, it does not build a range object.

If randrange(0,6) then it will return any number in range (0,1,2,3,4,5) please note that excluding 6.

Errors

The randrange function in python will raise ValueError in the following cases

Non-integer value for start, stop and step

# 1.5 is not integer so it will raise value error
random.randrange(1.5,5)

# 5.2 is not integer so it will raise value error
random.randrange(1,5.2)

# 1.5 step is not integer so it will raise value error
random.randrange(1,10,1.5)

Empty range for randrange

# This will raise empty range error as start(10) is higher than stop(5)
random.randrange(10,5)

# This will raise empty range error 
random.randrange(0)

If zero-step for randrange function

random.randrange(1,10,0)

Examples

import random

# Get a number from range 0 to 6
num = random.randrange(6)
print(f"Number : {num}")

Output

Number : 3

For instance, get an even number in the range of 0 to 100

import random

# Get an even number in the range 1 to 100
num = random.randrange(0,100,2)
print(f"Number : {num}")

Output

Number : 78

The randint function in python

This function returns an integer in the range.

Syntax

#Return a random integer N such that a <= N <= b  (From python doc)
random.randint(a, b)

This function is equivalent to randrange(a, b+1). In other words, the randrange function will not return stop number but randint can return the stop number (b).

Example

import random

for x in range(10):
    # Simulating dice roll
    num = random.randint(1,6)
    print(num)

Output

4
4
6
1
4
2
3
5
3
5

Conclusion

In conclusion, it is easier to get a random number from a range of numbers in python. To read about python list append vs extend performance comparison here.

Leave a Comment