Python Random Module – Python Tutorials

Welcome back, everyone. In this lecture, we’re going to discuss the Python built-in modules. That is the Python Random module.

The Python random module that contains a lot of mathematical random functions, as well as random functions for grabbing a random item from a python list.

But let’s explore these in more detail.

Python Random Module

Random Module allows us to create random numbers. We can even set a seed to produce the same random set every time.

The explanation of how a computer attempts to generate random numbers is beyond the scope of this course since it involves higher-level mathematics. But if you are interested in this topic check out:

Understanding a seed

Setting a seed allows us to start from a seeded pseudorandom number generator, which means the same random numbers will show up in a series. Note, you need the seed to be in the same cell if your using jupyter to guarantee the same results each time. Getting the same set of random numbers can be important in situations where you will be trying the different variations of functions and want to compare their performance on random values, but want to do it fairly (so you need the same set of random numbers each time).

Random integer

The function randint() returns a random integer between the given integer or specified integers. Example:

import random
random.randint(0,100)
Output: 62

Random with Sequences

Grab a random item from a list
mylist = list(range(0,20))
mylist
Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
python random module
Screenshot of above code

Random choice function in Python Random Module

This function random.choice() returns a randomly selected element or number from a non-empty sequence.Example:

random.choice(mylist)
Output:12

Sample with Replacement

Take a sample size, allowing picking elements more than once. Imagine a bag of numbered lottery balls, you reach in to grab a random lotto ball, then after marking down the number, you place it back in the bag, then continue picking another one. Example:

random.choices(population=mylist,k=10)
Output: [15, 14, 17, 8, 17, 2, 19, 17, 6, 1]

Sample without Replacement

Once an item has been randomly picked, it can’t be picked again. Imagine a bag of numbered lottery balls, you reach in to grab a random lotto ball, then after marking down the number, you leave it out of the bag, then continue picking another one. Example:

random.sample(population=mylist,k=10)
Output: [17, 19, 11, 14, 1, 3, 4, 10, 5, 15]

Must Read:


This is all about the Python Random Module, their different types, how to use with them with practical examples and also with snapshots. I hope you will like it.

Thank You 🙂

8 thoughts on “Python Random Module – Python Tutorials

Leave a Reply

Your email address will not be published. Required fields are marked *