On this page
  1. random
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Reproducible Isolated Generators (random.Random(seed))
  7. 2. Weighted Sampling With Replacement (choices) vs. Without Replacement (sample)
  8. Gotchas & Boundaries
  9. Common Functions
  10. Classes & Objects

random

Prev: quopri | Up: stdlib_module | Next: re
Rel: numbers, math, cmath, decimal, fractions
Ref: docs.python.org — random
Tags: #public #python3 #stdlib


Import

import random

Overview

Fast Mersenne Twister pseudo-random number generator for simulations, games, sampling, shuffling, and randomized tests (randint, randrange, choice, choices, sample, shuffle, uniform, gauss). Never use random for security, passwords, or tokens—use secrets for cryptographic randomness.

Quick Start

import random

rng = random.Random(42)  # isolated, reproducible generator
assert rng.randint(1, 6) == 6
assert rng.choice(["rock", "paper", "scissors"]) in {"rock", "paper", "scissors"}
assert len(rng.sample(range(100), k=5)) == 5

Implementation Walkthrough

1. Reproducible Isolated Generators (random.Random(seed))

In libraries and tests, instantiate random.Random(seed) instead of calling random.seed(...) globally so unrelated modules never interfere with your sequence:

import random

def deal_hand(seed: int) -> list[int]:
    rng = random.Random(seed)
    deck = list(range(52))
    rng.shuffle(deck)
    return deck[:5]

assert deal_hand(7) == deal_hand(7)

2. Weighted Sampling With Replacement (choices) vs. Without Replacement (sample)

import random

rng = random.Random(0)
# With replacement and weights:
draws = rng.choices(["common", "rare", "epic"], weights=[80, 18, 2], k=10)
# Without replacement (unique picks):
winners = rng.sample(["Ada", "Lin", "Grace", "Alan"], k=2)
assert len(draws) == 10 and len(set(winners)) == 2

Gotchas & Boundaries

Common Functions

Classes & Objects

Linked from

Related notes