What is the random module in Python?

random is a built-in module in Python that provides basic functions to generate pseudorandom numbers. It allows us to use randomness in our program by generating random numbers by selecting random elements from a sequence, shuffling sequences, and more.

Importing and using the random module

The random module can be used directly by importing it into our system without installing any prerequisites. The following part of the code can be used at the start of the code:

import random

random module’s functions

There is a range of functions that random modules provides us to use in our code. The following are a few of those functions:

  • random(): It generates a random number between 00 and 11.
  • randint(a, b): It generates a random number between a and b.
  • choice(seq): It selects a random number from the non-empty sequence, seq.
  • shuffle(x): It shuffles the elements x in places.

Example

Below are the coding examples of the aforementioned functions that the random module provides.

import random
# random()
random_number = random.random()
print("Random number between 0 and 1:", random_number)
# randint(a, b)
random_integer = random.randint(1, 10)
print("Random integer between 1 and 10:", random_integer)
# choice(seq)
numbers = [1, 2, 3, 4, 5]
random_choice = random.choice(numbers)
print("Random choice from the list:", random_choice)
# shuffle(x)
my_list = [1, 2, 3, 4, 5]
random.shuffle(my_list)
print("Shuffled list:", my_list)

Code explanation

  • Line 1: It imports the random module in our program.

  • Lines 4–5: It generates a random number between 00 and 11.

  • Lines 8–9: It uses randint() to generate a number between 1 and 10.

  • Lines 12–14: It selects a random number from the number list.

  • Lines 17–19: It shuffles the list using the shuffle function.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved