LearnContact
Lesson 5024 min read

Random Module

Learn how to generate random numbers, make random choices, and shuffle data in Python using the random module.

Introduction

Randomness shows up everywhere in programming — shuffling a deck of cards, picking a random quiz question, simulating a dice roll, or selecting a random winner from a list of entries. Python's built-in random module makes all of this straightforward.

This lesson covers the most commonly used functions in the random module: generating random numbers, picking random items, shuffling sequences, and making randomness reproducible for testing.

What You Will Learn
  • How to generate a random float with random.random().
  • How to generate a random integer with random.randint().
  • How to pick a random item with random.choice().
  • How to shuffle a list in place with random.shuffle().
  • How to pick multiple unique items with random.sample().
  • How to make randomness reproducible using random.seed().

The random Module

The random module is part of Python's standard library. It generates pseudo-random numbers — values that appear random but are actually produced by a deterministic algorithm based on an internal starting value called a seed.

import random

print(random.random())
Output
0.7364216436258961

Your output will be a different number every time you run this, since it is based on the current system state by default.

random.random()

random.random() returns a random float between 0.0 (inclusive) and 1.0 (exclusive). It is the foundation many other random functions are built on.

import random

for _ in range(3):
    print(random.random())
Output
0.4370861069626263
0.8686465656500981
0.09767211400638387

random.randint(a, b)

random.randint(a, b) returns a random integer N such that a <= N <= b — note that both endpoints are included, unlike Python's range().

import random

dice_roll = random.randint(1, 6)
print("You rolled:", dice_roll)

for _ in range(5):
    print(random.randint(1, 100), end=" ")
Output
You rolled: 4
83 12 67 5 91 

random.choice(sequence)

random.choice() picks and returns a single random element from a non-empty sequence, such as a list or tuple.

import random

colors = ["red", "green", "blue", "yellow"]
print(random.choice(colors))

players = ["Alice", "Bob", "Charlie", "Dana"]
print("First turn goes to:", random.choice(players))
Output
blue
First turn goes to: Charlie

random.shuffle(list)

random.shuffle() rearranges the elements of a list randomly, in place — meaning it modifies the original list directly and returns None.

import random

cards = ["A", "K", "Q", "J", "10"]
random.shuffle(cards)
print(cards)
Output
['Q', '10', 'A', 'J', 'K']
shuffle() Returns None

random.shuffle(cards) modifies cards directly. Writing cards = random.shuffle(cards) will set cards to None, which is a common beginner mistake.

random.sample(population, k)

random.sample() returns a new list containing k unique elements chosen from the population, without modifying the original sequence and without repeating any element.

import random

lottery_numbers = list(range(1, 50))
winning_numbers = random.sample(lottery_numbers, 6)
print(sorted(winning_numbers))
Output
[3, 11, 22, 29, 34, 47]

Unlike random.choice(), which can select the same item repeatedly if called multiple times, random.sample() guarantees every selected item is unique.

Reproducibility with random.seed()

By default, "random" numbers differ every run. Sometimes — especially for testing or demonstrations — you want the same sequence of "random" results every time. random.seed(value) makes this possible by resetting the internal state to a known starting point.

import random

random.seed(42)
print(random.randint(1, 100))
print(random.randint(1, 100))

random.seed(42)
print(random.randint(1, 100))   # same as the first call above
print(random.randint(1, 100))   # same as the second call above
Output
82
15
82
15
Why Seed?
  • Makes test results reproducible and predictable.
  • Lets you debug "random" behavior consistently.
  • Should generally be avoided in production randomness like security tokens.

Practical Example: Dice Roll and Random Winner

Let's combine these functions into two small practical programs: simulating rolling two dice, and picking a random winner from a list of contest entries.

dice_roll.py
import random

def roll_dice():
    die1 = random.randint(1, 6)
    die2 = random.randint(1, 6)
    return die1, die2

d1, d2 = roll_dice()
print(f"You rolled {d1} and {d2}. Total: {d1 + d2}")
Output
You rolled 4 and 2. Total: 6
random_winner.py
import random

entries = ["Alex", "Sam", "Priya", "Jordan", "Morgan"]
winner = random.choice(entries)
print(f"The winner is: {winner}!")
Output
The winner is: Priya!

Common Mistakes

Avoid These Mistakes
  • Writing my_list = random.shuffle(my_list), which sets my_list to None.
  • Using random.choice() when you need several unique items — use random.sample() instead to avoid duplicates.
  • Forgetting that random.randint(a, b) includes both a and b, unlike range(a, b).
  • Assuming random.seed() makes results identical across different Python versions — it is only guaranteed within the same version.
  • Using the random module for security-sensitive purposes like passwords or tokens — use the secrets module for those instead.

Best Practices

  • Use random.sample() instead of a loop with random.choice() when you need unique picks.
  • Use random.seed() in tests and tutorials so results are reproducible.
  • Never use the random module for cryptographic or security purposes — use secrets instead.
  • Remember random.shuffle() modifies a list in place and returns None.
  • Use random.randint() for inclusive integer ranges and random.random() when you need a float between 0 and 1.

Frequently Asked Questions

What is the difference between random.choice() and random.sample()?

random.choice() picks one item and can be called repeatedly, potentially returning the same item more than once. random.sample() picks several unique items at once, guaranteeing no duplicates.

Does random.randint(1, 6) include 6 as a possible result?

Yes. Unlike range(), random.randint(a, b) is inclusive of both endpoints, so random.randint(1, 6) can return 1, 2, 3, 4, 5, or 6.

Why would I want reproducible randomness?

For testing, debugging, or teaching, it is often useful to get the exact same "random" sequence every run. random.seed(value) achieves this by resetting the generator to a known state.

Is the random module safe for generating passwords?

No. The random module is not cryptographically secure. For passwords, tokens, or anything security-related, use Python's secrets module instead.

Does random.shuffle() work on a tuple?

No, tuples are immutable so they cannot be shuffled in place. random.shuffle() only works on mutable sequences like lists.

Key Takeaways

  • random.random() returns a float between 0.0 and 1.0.
  • random.randint(a, b) returns a random integer, inclusive of both endpoints.
  • random.choice() picks one item; random.sample() picks several unique items.
  • random.shuffle() reorders a list in place and returns None.
  • random.seed() makes randomness reproducible, which is useful for testing.

Summary

The random module gives Python simple, reliable tools for generating randomness — from single random numbers to shuffling entire collections — which power everything from games to simulations to random sampling.

In this lesson, you learned how to generate random numbers, pick random items, shuffle sequences, and make randomness reproducible using seeds.

Lesson Completed
  • You can generate random numbers and make random selections.
  • You understand the difference between choice(), sample(), and shuffle().
  • You know how to use seed() for reproducible results.
  • You are ready to explore Python's os module.
Next Lesson →

OS Module