How to Use Random Module in Python

09/08/2021

Contents

In this article, you will learn how to use random module in Python.

Python Random Module

The random module in Python provides a suite of functions for generating random numbers and doing random selections from sequences.

Here are some common ways to use the random module in Python:

Generating random numbers

The random module has methods to genere random numbers:

  • random.random(): Generates a random float between 0 and 1.
  • random.uniform(a, b): Generates a random float between a and b.
  • random.randint(a, b): Fenerates a random integer between a and b, including both endpoints.
  • random.randrange(start, stop, step): Generates a random integer between start and stop, excluding stop and incrementing by step.

Shuffling lists

The random module has a method to shuffle lists:

  • random.shuffle(sequence): Shuffles the elements in a sequence in place.

Selecting random elements

The random module has methods to select random elements:

  • random.choice(sequence): Selects a random element from a non-empty sequence.
  • random.sample(sequence, k): Selects k unique elements from a sequence at random and returns them as a list.

Here’s an example of how you could use the random module to generate a random number and shuffle a list:

import random

# Generating a random number
random_float = random.random()
print(random_float)

# Shuffling a list
my_list = [1, 2, 3, 4, 5]
random.shuffle(my_list)
print(my_list)