- Python random randrange() and randint() to generate random integer number within a range
- Table of contents
- How to use random.randint()
- random.randint() example of generating random number
- random.randrange() to generate random integers within a range
- Syntax
- random.randrange() examples
- Random number of a specific length
- Random integer number multiple of n
- Random negative integer
- Generate random positive or negative integer
- Randomly generate 1 or -1
- Generate a list of random integer numbers
- Create a list of random numbers without duplicates
- Sort random numbers list
- Generate a secure random integer
- Create a multidimensional array of random integers
- Points to remember about randint() and randrange()
- Next Steps
- About Vishal
- Related Tutorial Topics:
- Python Exercises and Quizzes
Python random randrange() and randint() to generate random integer number within a range
In this lesson, we will see how to use the randrange() and randint() functions of a Python random module to generate a random integer number.
Using randrange() and randint() functions of a random module, we can generate a random integer within a range. In this lesson, you’ll learn the following functions to generate random numbers in Python. We will see each one of them with examples.
Function | Description |
---|---|
random.randint(0, 9) | Returns any random integer from 0 to 9 |
random.randrange(20) | Returns a random integer from 0 to 19 |
random.randrange(2, 20) | Returns a random integer from 2 to 19. |
random.randrange(100, 1000, 3) | Returns any random integer from 100 to 999 with step 3. For example, any number from 100, 103, 106 … 994, 997. |
random.randrange(-50, -5) | Returns a random negative integer between -50 to -6. |
random.sample(range(0, 1000), 10) | Returns a list of random numbers |
secrets.randbelow(10) | Returns a secure random number |
functions to generate random numbers
Table of contents
How to use random.randint()
This function returns a random integer between a given start and stop integer.
It takes two parameters. Both are mandatory.
- start : It is the start position of a range. The default value is 0 if not specified.
- stop : It is the end position of a range.
Return value:
It will generate any random integer number from the inclusive range. The randint(start, stop) consider both the start and stop numbers while generating random integers
How to use Python randint() and randrange() to get random integers
- Import random module Use Python’s random module to work with random data generation.
import it using a import random statement. - Use randint() Generate random integer Use a random.randint() function to get a random integer number from the inclusive range. For example, random.randint(0, 10) will return a random number from [0, 1, 2, 3, 4, 5, 6, 7, 8 ,9, 10].
- Use the randrnage() function to generate a random integer within a range Use a random.randrange() function to get a random integer number from the given exclusive range by specifying the increment. For example, random.randrange(0, 10, 2) will return any random number between 0 and 20 (like 0, 2, 4, 6, 8).
random.randint() example of generating random number
import random # random integer from 0 to 9 num1 = random.randint(0, 9) print(num1) # output 5 # Random integer from 10 to 100 num2 = random.randint(10, 100) print(num2) # Output 84
Note: You cannot use float numbers in randint() . It will raise a ValueError ( non-integer stop for randrange() ) if you use non-integer numbers. Please, read how to generate a random float number within a range.
random.randrange() to generate random integers within a range
Now let’s see how to use the random.randrange() function to get a random integer number from the given exclusive range by specifying the increment.
Syntax
random.randrange(start, stop[, step])
This function returns a random integer from a range(start, stop, step) . For example, random.randrange(0, 10, 2) will generate any random numbers from [0, 2, 4, 6, 8].
It takes three parameters. Out of three, two parameters are optional. i.e., start and step are optional.
- start : it is the star number in a range. i.e., lower limit. The default value is 0 if not specified.
- stop : It is the end/last number in a range. It is the upper limit.
- step : Specify the increment value in range. The generated random number is divisible by step. The default value is 1 if not specified.
random.randrange() examples
In the following example, we are trying to print a random int in a given range. This example demonstrates all the variants of random.randrange() function.
import random # random integer from 0 to 9 num1 = random.randint(0, 9) print(num1) # output 5 # Random integer from 10 to 100 num2 = random.randint(10, 100) print(num2) # Output 84
- The randrange() doesn’t consider the stop number while generating a random integer. It is an exclusive random range. For example, randrange(2, 20, 2) will return any random number between 2 to 20, such as 2, 4, 6, …18. It will never select 20.
- Same as randint() , you cannot use float value in randrange() too. It will raise a ValueError (non-integer arg 1 for randrange()) if you use non-integers.
Random number of a specific length
Let’s see how to generate a random number of length n. For example, any random number of length four, such as 7523, 3674. We can accomplish this using both randint() randrange() .
import random # random number of length 4 num1 = random.randint(1000, 9999) # random number of length 4 with step 2 num2 = random.randrange(1000, 10000, 2) print(num1, num2) # Output 3457 5116
Note: As you can see, we set a start = 1000 and a stop = 10000 because we want to generate the random number of length 4 (from 1000 to 9999).
Random integer number multiple of n
For example, let’s generate a random number between x and y multiple of 3 like 3, 6, 39, 66.
import random num = random.randrange(3, 300, 3) print(num) # output 144
Random negative integer
Let’s see how to generate a random negative integer between -60 to -6.
import random singed_int = random.randrange(-60, -6) print(singed_int) # Output -16
Generate random positive or negative integer
import random for i in range(5): print(random.randint(-10, 10), end=' ') # Output 10 -1 5 -10 -7
Randomly generate 1 or -1
import random num = random.choice([-1, 1]) print(num)
Note: we used random.choice() to choose a single number from the list of numbers. Here our list is [-1, 1] .
Generate a list of random integer numbers
In this section, we will see how to generate multiple random numbers. Sometimes we need a sample list to perform testing. In this case, instead of creating it manually, we can create a list with random integers using a randint() or randrange() . In this example, we will see how to create a list of 10 random integers.
import random random_list = [] # Set a length of the list to 10 for i in range(0, 10): # any random numbers from 0 to 1000 random_list.append(random.randint(0, 1000)) print(random_list) # Output [994, 287, 65, 994, 936, 462, 839, 160, 689, 624]
Create a list of random numbers without duplicates
Note: In the above example, there is a chance of occurring a duplicate number in a list.
If you want to make sure each number in the list is unique, use the random.sample() method to generate a list of unique random numbers.
- The sample() returns a sampled list of selected random numbers within a range of values.
- It never repeats the element so that we can get a list of random numbers without duplicates
import random # Generate 10 unique random numbers within a range num_list = random.sample(range(0, 1000), 10) print(num_list) # Output [499, 580, 735, 784, 574, 511, 704, 637, 472, 211]
Note: You can also use the step parameter of the range() function to specify the increment. For example, you want a list of 10 random numbers, but each integer in a list must be divisible by 5, then use random.sample(range(0, 1000, 5), 10)
Sort random numbers list
Use the sort() function to sort a list of random integers in ascending order
import random sample_list = random.sample(range(50, 500, 5), 5) # Before sorting print(sample_list) # Output [305, 240, 260, 235, 445] sample_list.sort() # After sorting print(sample_list) # Output [235, 240, 260, 305, 445]
Generate a secure random integer
Above all, examples are not cryptographically secure. The cryptographically secure random generator generates random numbers using synchronization methods to ensure that no two processes can obtain the same number simultaneously.
If you are producing random numbers for a security-sensitive application, then you must use this approach.
Use the secrets module if you are using a Python version higher than 3.6.
import secrets # secure random integer # from 0 to 10 secure_num = secrets.randbelow(10) print(secure_num) # Output 5
If you are using Python version less than 3.6, then use the random.SystemRandom().randint() or random.SystemRandom().randrange() functions.
Create a multidimensional array of random integers
Python’s NumPy module has a numpy.random package to generate random data. To create a random multidimensional array of integers within a given range, we can use the following NumPy methods:
- randint()
- random_integers()
- np.randint(low[, high, size, dtype]) to get random integers array from low (inclusive) to high (exclusive).
- np.random_integers(low[, high, size]) to get random integer’s array between low and high, inclusive.
Generate a 4 x 4 array of ints between 10 and 50, exclusive:
import numpy # 4 x 4 array newArray = numpy.random.randint(10, 50, size=(4, 4)) print(newArray)
[[10 48 30 24] [13 46 30 11] [12 28 49 26] [30 18 49 35]]
Generate a 5 x 3 array of random integers between 60 and 100, inclusive.
import numpy # 3 x 5 array of ints newArray = numpy.random.random_integers(60, 100, size=(3, 5)) print(newArray)
[[63 76 95 93 75] [71 84 63 99 93] [65 64 66 69 92]]
Points to remember about randint() and randrange()
- Use randint() when you want to generate a random number from an inclusive range.
- Use randrange() when you want to generate a random number within a range by specifying the increment. It produces a random number from an exclusive range.
You should be aware of some value constraints of a randrange() function.
- The randint( ) rand randrange() works only with integers. You cannot use float numbers.
- The step must not be 0. If it is set to 0, you will get a ValueError: zero step for randrange()
- The start should not be greater than stop if you are using all positive numbers. If you set start greater than stop, you will get a ValueError: empty range for randrange()
import random # ValueError: empty range for randrange() print(random.randrange(100, 10, 2))
But, you can also set a start value greater than stop if you are using a negative step value.
import random print(random.randrange(100, 10, -2)) # output 60
Next Steps
I want to hear from you. What do you think of this article on randint() and randrange() ? Or maybe I missed one of the usages of those two functions. Either way, let me know by leaving a comment below.
Also, try to solve the following exercise and quiz to have a better understanding of working with random data in Python.
- Python random data generation Exercise to practice and master the random data generation techniques in Python.
- Python random data generation Quiz to test your random data generation concepts.
Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.
About Vishal
I’m Vishal Hule, Founder of PYnative.com. I am a Python developer, and I love to write articles to help students, developers, and learners. Follow me on Twitter
Related Tutorial Topics:
Python Exercises and Quizzes
Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.
- 15+ Topic-specific Exercises and Quizzes
- Each Exercise contains 10 questions
- Each Quiz contains 12-15 MCQ