How to Generate Random Integers in Range in Python
Python is a popular programming language when working with math and data because of how easy it is to work with numbers.
A popular operation in Python is to generate random numbers in a specific range so that you can use it in your code.
In this post, we'll learn how to generate random numbers in a specific range in Python.
A simple way to generate random numbers in a specific range is to use the
This function comes from the
random module and you can use it by just importing it.
Let's look at how to generate a random number between 0 and 10 in Python:
import random number = random.randint(0, 10) print(number)
Keep in mind that this will include the number
0 but exclude the number
Now, if you want to generate a list of these numbers, you can use the
import random numbers = [random.randint(0, 10) for p in range(0, 10)] print(numbers)
[1, 8, 4, 0, 5, 9, 2, 3, 6, 8]
Here is the general syntax:
import random range_start = 0 range_end = 10 gen_count = 10 numbers = [random.randint(range_start, range_end) for p in range(0, gen_count)] print(numbers)
Another function that comes with the
random module is
This function also requires a start and end range, however, it also allows you to specify a step size.
step parameter is optional, but if you don't specify it, it will default to
This parameter controls the step size of the range, so if you want to generate a list of numbers between 0 and 10, but only in steps of 2, you can use the following syntax:
import random numbers = [random.randrange(0, 10, 2) for p in range(0, 10)] print(numbers)
[4, 2, 6, 2, 4, 8, 6, 4, 2, 2]
When you want to ensure that you have a random list of unique numbers, you can use the
This function will generate a random list of integers for you while ensuring they are all unique.
Let's see how it works:
import random numbers = random.sample(range(0, 10), 10) print(numbers)
[4, 3, 8, 1, 7, 2, 9, 6, 0, 5]
In this post, we learned how to generate random numbers in a specific range in Python.
Python has several built-in functions that you can use to generate the random numbers that you need. Simply pick the one that is right for your use-case.
Thanks for reading and happy coding!
If you want to learn about web development, founding a start-up, bootstrapping a SaaS, and more, follow me on Twitter! You can also join the conversation over at our official Discord!
Leave us a message!