How to Generate Random Integers in Range in Python

Updated onbyAlan Morel
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.

Using random.randint()

A simple way to generate random numbers in a specific range is to use the randint() function.

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)
5

Keep in mind that this will include the number 0 but exclude the number 10.

Now, if you want to generate a list of these numbers, you can use the range() function:

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)

Using random.randrange()

Another function that comes with the random module is randrange().

This function also requires a start and end range, however, it also allows you to specify a step size.

The step parameter is optional, but if you don't specify it, it will default to 1.

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]

Using random.sample()

When you want to ensure that you have a random list of unique numbers, you can use the sample() function.

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]

Conclusion

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!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.