How to Generate Random Integers in Python?

Rate this post

The most idiomatic way to create a random integer in Python is the randint() function of the random module. Its two arguments start and end define the range of the generated integers. The return value is a random integer in the interval [start, end] including both interval boundaries. For example, randint(0, 9) returns an integer in 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9.

Let’s explore a couple of examples next.

Generate a Random Integer Between 0 and 9

To create a random integer between 0 and 9, call random.randint(0, 9).

import random
num = random.randint(0, 9)

The output can be any number between 0 (included) and 9 (included).

Generate a Random Integer Between 1 and 10

To create a random integer between 1 and 10, call random.randint(1, 10).

import random
num = random.randint(1, 10)

The output can be any number between 1 (included) and 10 (included).

Generate a Random Integer Between 1 and 100

To create a random integer between 1 and 100, call random.randint(1, 100).

import random
num = random.randint(1, 100)

The output can be any number between 1 (included) and 100 (included).

Generate a Random Integer Between x and y

To create a random integer num between x and y so that x <= num <= y holds, call random.randint(x, y).

import random
x, y = 0, 10
num = random.randint(x, y)

The output can be any number between x (included) and y (included).

randrange()

An alternative way to create random integers within a certain range in Python is the random.randrange() function. This allows you more flexibility to define the range from which the random numbers should be drawn.

Here’s the usage overview with three different sets of arguments:

UsageDescription
randrange(stop)Return a randomly selected element from range(0, stop, 1)
randrange(start, stop)Return a randomly selected element from range(start, stop, 1)
randrange(start, stop, step)Return a randomly selected element from range(start, stop, step)

Here are three example runs in my Python shell:

>>> import random
>>> random.randrange(3)
1
>>> random.randrange(2, 3)
2
>>> random.randrange(2, 10, 2)
2

If you want to master the random module, check out the following video and our in-depth guide on the Finxter blog.