All You Should Know About Python Random Module

Python Code Examples

A random number is the outcome of a process which arbitrarily chooses it from a sequence. It is called random number generation. With Python random module, we can generate random numbers to fulfill different programming needs. It has a no. of functions like randint(), random(), choice(), uniform() that as a programmer we can decide to use depending on the use case.

At the core, Python uses Mersenne Twister algorithm, a pseudo-random generator (PRNG) to generate pseudo-random numbers. Its ability to produce uniform results makes it suitable for many applications. Knowing this fact is important as this would help us determine when to use it and where not.

Studies reveal that PRNGs are suitable for applications such as simulation and modeling but not recommended for cryptographic purposes. And the same rule applies for the Python random no. generator. However, we can use it for programming tasks like generating random integers between a range, randomly select an item from a list or shuffle a sequence in place.

Let's now check out the most used functions of Python random module and their examples.

Using Python random module to generate random numbers

Python Random - Generate Random Numbers.

Table of Content.

Generate Random Integers in Python.

Following three functions allow generating random integers in Python.

1. Python randrange() function.

This function has following two variations.

Python randrange(stop) function.

Purpose- It will produce a random integer value less than the value specified by the [stop] argument.

If "r" is a random number, then its value will lie in the range 0 <= r < stop.



[stop] - It is the boundary value of the range to be used for generating the random number. Pass a valid integer value only.

You can't pass a zero or a negative value or a floating point number to this function as it'll throw the ValueError exception.

Python randrange() example.

import random


Python randrange(start, stop[, step]) function.

Purpose- It uses the following range [start, stop-1] to return a uniquely selected integer value. If the [step] is specified, then the randrange() output is incremented by it.

If "r" is a random number, then its value will lie in the range start <= r < stop.


random.randrange(start, stop[, step])

[start] - It is the base value of the range and may fall in the selection.

[stop] - It is the boundary value of the range excluding from the selection.

[step] - It is the value with which the number is incremented. The default value is 0 if not passed.

Python randrange() example.

import random

# Generate random integer in the interval [4,10]

# Generate random integer in [4,10] with increment of 3
print(random.randrange(4, 11, 3))

# Generate random even numbers between 2 and 24
print(random.randrange(2, 25, 2))

# Generate random even numbers between 1 and 25
print(random.randrange(1, 26, 2))


#1.     #2.     #3.
10	7	4
4	10	4
4	12	8
17	3	23

Back to top

2. Python random.randint(low, high)  function.

Purpose- The randint() function is one of many functions which handle random numbers. It has two parameters low and high and generates an integer between low and high (including both).

Python randint() example.

# Generate random integers in range 0 through 9.
import random

iter = 0
while iter < 10:
 # Get random number in range 0 through 9.
 r = random.randint(0, 9)
 iter += 1


0 Low value
9 High value

Back to top

Choose a random number from the sequence.

3. Python random.choice(seq) function.

Purpose- The choice() function arbitrarily determines an element from the given sequence.

Note- A sequence in Python is the generic term for an ordered set like a list, tuple etc.

Python choice() example.

# How to use Python's choice() function to select a item.
import random

# Generate a random string from the list of strings

print(random.choice( ['Python', 'C++', 'Java'] ))

# Generate a random number from the list [-1, 1, 3.5, 7, 15]

print(random.choice([-1, 1, 3.5, 9, 15]))

# Generate a random number from a uniformly distributed tuple

print(random.choice((1.1, -5, 6, 4, 7)))

# Generate a random char from a string

print(random.choice('Learn Python Programming'))

Back to top

4. Python random.shuffle(list) function.

Purpose- The shuffle() function rearranges the items of a list in place so that they occur in a random order.

For shuffling, it uses the Fisher-Yates algorithm which has O(n) complexity. It starts by iterating the last element in the array to the first entry, then swap each entry with an entry at a random index below it.

Python shuffle() example.

# How to randomize a list in Python?
from random import shuffle

mylist = [11,21,31,41,51]



#1. [41, 51, 11, 31, 21]

#2. [11, 31, 41, 51, 21]

Back to top

5. Python random.sample(collection, random list length) function.

Purpose- The sample() function randomly selects N items from a given collection (list, tuple, string, dictionary, set) and returns them as a list.

It works by sampling the items without replacement. It means a single element from the sequence can appear in the resultant list at most once.

Python sample() example.

# How to use sample() in Python?
from random import sample

# Select any three chars from a string


# Randomly select a tuple of three elements from a base tuple

print(sample((21, 12, -31, 24, 65, 16.3), 3))

# Randomly select a list of three elements from a base list

print(sample([11, 12, 13, 14, -11, -12, -13, -14], 3))

# Randomly select a subset of size three from a given set of numbers

print(sample({110, 120, 130, 140}, 3))

# Randomly select a subset of size three from a given set of strings

print(sample({'Python', 'C++', 'Java', 'Go'}, 3))


['y', 'o', 't']
[21, 12, 24]
[-14, 14, -13]
[140, 110, 130]
['Python', 'Java', 'C++']

Back to top

Generating Floating point random numbers.

6. Python random.random() function.

Purpose- It selects the next random floating point number from the range [0.0, 1.0]. It is a semi-open range as the random function will always return a decimal no. less than its upper bound. However, it may return 0.

Python random() example.

# How to generate a floating-point random number in Python?
import random

# Generate a floating-point pseudo-random number between 0 and 1.



#1. 0.4968601882231284

#2. 0.831505293496292

Back to top

7. Python random.uniform(lower, upper) function.

Purpose- It is an extension of the random() function. In this, you can specify the lower and upper bounds to generate a random number other than the ones between 0 and 1.

Python uniform() example-1.

# How to uniform() method to generate floating-point random numbers?
import random

lower = 111; upper = 999
random_float = random.uniform(lower, upper)


#1. 466.63369297787557

#2. 315.3719206118211

Python uniform() example-2.

# Generate a floating-point random number with fixed precision
import random

lower = 1.0; upper = 2.0; fixed_precision = 2

random_float = random.uniform(lower, upper)

print(round(random_float, fixed_precision))


#1. 1.48

#2. 1.69

#3. 1.57

Back to top

Quick Wrap-up.

We've tried to portray the use of Python random module and its functions in a much-simplified manner. Our purpose was to make it utterly simple so that even a newbie could understand it easily.

In this tutorial, we covered the most commonly used Python functions to generate random numbers. However, the Python random module also provides functions for advanced random distributions. These include Exponential, Gamma, Gauss, Lognormal, and Pareto distributions.

If you like us to write on any of these advanced topics, then do let us know. And if you liked this post and are interested in seeing more such posts, then follow us on our social media (Facebook/Twitter) accounts.