Skip to content

Module 15 · Python Standard Libraries — topic 2 of 13

random

Pseudo-random numbers with random: integers and floats, choosing and shuffling, sampling without replacement, weighted choices, seeding for reproducibility, separate Random instances, and why secrets is for security.

Beginner 8 min read·Lesson 223 of 306 in Python Programming

Learning objectives

  • Generate random numbers, choices and samples
  • Make random results reproducible with seeds
  • Know when to use secrets instead

Definition

random generates pseudo-random numbers using a deterministic algorithm (the Mersenne Twister). Seeding it with the same value produces the same sequence, which is useful for simulations and tests.

Introduction

Games, simulations, test data and quizzes need randomness. The random module provides it — and can repeat the same 'random' run when you need to debug.

Why it matters

Seeded randomness makes simulations repeatable, while knowing its limits keeps you from using it for passwords or tokens.

Detailed explanation

random.randint(a, b) returns an integer from a to b inclusive; randrange(start, stop, step) works like range.

random.random() returns a float in [0.0, 1.0); uniform(a, b) a float between a and b.

choice(seq) picks one item; choices(seq, weights=..., k=n) picks n items with replacement, optionally weighted; sample(seq, k) picks k distinct items.

shuffle(list) reorders a list in place and returns None.

random.seed(value) resets the generator, so the following calls repeat exactly — helpful for tests and reproducible experiments.

random.Random(seed) creates an independent generator, so different parts of a program don't disturb each other's sequences.

These numbers are predictable. For passwords, tokens and anything security-related, use the secrets module.

Syntax

Python
import random
random.seed(42)
random.randint(1, 6)
random.choice(["a", "b"])
random.sample(range(100), 5)
random.shuffle(items)
  • Seed for reproducible results.
  • sample: no repeats; choices: repeats allowed.
  • shuffle works in place.

Code examples

Seeded numbers

Python
import random
random.seed(42)
print(random.randint(1, 6), random.randint(1, 6), random.randint(1, 6))
print(round(random.random(), 4), round(random.uniform(10, 20), 2))
Output
6 1 1
0.7416 12.45

Choosing, shuffling and sampling

Python
import random
random.seed(7)
colors = ["red", "green", "blue", "yellow"]
print(random.choice(colors))
random.shuffle(colors)
print(colors)
print(random.sample(range(1, 50), 6))
Output
blue
['blue', 'red', 'yellow', 'green']
[5, 35, 7, 24, 38, 4]

More examples

A dice simulation

Python
import random
from collections import Counter
rng = random.Random(2026)
rolls = [rng.randint(1, 6) + rng.randint(1, 6) for _ in range(10_000)]
counts = Counter(rolls)
print(counts.most_common(1)[0][0], min(counts), max(counts))
print(round(sum(r == 7 for r in rolls) / len(rolls), 2))
print(rng.choices(["win", "draw", "lose"], weights=[3, 2, 5], k=8))
Output
7 2 12
0.16
['win', 'draw', 'lose', 'win', 'draw', 'lose', 'lose', 'win']

Step-by-step explanation

  • A separate Random(2026) instance gives a reproducible sequence without touching the global generator.
  • Over 10,000 rolls of two dice, 7 is the most common total, with a frequency close to the theoretical 1/6.
  • choices with weights picks outcomes in proportion 3 : 2 : 5.

Expected output

Running “A dice simulation” prints exactly:

TextOutput
7 2 12
0.16
['win', 'draw', 'lose', 'win', 'draw', 'lose', 'lose', 'win']

Practical applications

  • Shuffling quiz questions and answer options.
  • Monte Carlo simulations and generating test data.

Best practices

  • Seed or use Random instances for reproducible runs.
  • Use sample for distinct items.
  • Use secrets for anything security-related.

Common mistakes

Random for security

Avoid

token = str(random.randint(100000, 999999))

Prefer

import secrets
token = secrets.token_urlsafe(16)

random is predictable; secrets uses the operating system's secure source.

Using shuffle's return value

Avoid

deck = random.shuffle(deck) # deck becomes None

Prefer

random.shuffle(deck)

shuffle changes the list in place and returns None.

Important notes

  • Exact values for a given seed can change between Python versions for some functions; don't hard-code them in long-lived tests.

Key takeaways

  • randint, random, choice, choices, sample, shuffle.
  • seed makes sequences repeatable.
  • secrets for security.

Try it yourself

  1. 1
    Simulate 1,000 coin tosses and report the proportion of heads.
  2. 2
    Write a function that deals a hand of 5 cards from a shuffled deck.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • ModerateWhy call random.seed(42) before generating numbers in a test?
Practise this topic