Randomness with the random Module

Published by Brayan K

The random module is Python's standard toolkit for generating pseudo-random numbers, picking and shuffling items, and reproducing the same sequence on demand with a seed.

Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

A seed starts a sequence; it does not freeze each draw

A game or simulation often needs unpredictable-looking choices that can be reproduced when a bug occurs. A Random object has its own internal state. Supplying a seed chooses a starting state; each draw advances it. Two separate generators with the same seed and the same calls can reproduce each other without changing unrelated code's generator.

from random import Random

left = Random(42)
right = Random(42)
# Consume the same sequence of operations from each independent object.
left_values = [left.random() for _ in range(3)]
right_values = [right.random() for _ in range(3)]
print(left_values == right_values)
print(len(set(left_values)))
print(all(0 <= value < 1 for value in left_values))

# ✅ Expected output:
# True
# 3
# True

The seed is not an instruction to return the same value on every call. Recreating a generator inside a loop does restart it, which is usually a bug:

from random import Random

restarted = [Random(42).random() for _ in range(3)]
generator = Random(42)
continued = [generator.random() for _ in range(3)]
print(len(set(restarted)))
print(len(set(continued)))

# ✅ Expected output:
# 1
# 3

These examples use fixed seeds and print properties of the results, so their panels do not depend on a clock or a lucky draw. Python documents a reproducibility guarantee for the compatible seeded random() stream; higher-level algorithms can change across releases. Save the interpreter version and the sequence of operations when exact replay matters, rather than promising that every helper has an eternal output sequence.

Read the interval before choosing a number

rng.random() gives a float at least zero and strictly below one. rng.randrange(start, stop) chooses from the integers that range(start, stop) would contain, excluding stop. rng.randint(a, b) includes both endpoints. A die uses randint(1, 6), not randrange(1, 6).

from random import Random

rng = Random(17)
rolls = [rng.randint(1, 6) for _ in range(20)]
even = [rng.randrange(0, 10, 2) for _ in range(20)]
print(all(1 <= value <= 6 for value in rolls))
print(all(value in range(0, 10, 2) for value in even))
print(rng.randint(6, 6))

# ✅ Expected output:
# True
# True
# 6

The assertions about allowed values describe the contract; twenty draws are not a statistical proof of fairness. An empty interval has no number to choose. For example, randrange(5, 5) raises ValueError rather than inventing an endpoint. Choose a valid range before drawing, especially when limits come from user input.

Decide whether a selected item can be selected again

choice(sequence) picks one item. choices(sequence, k=n) performs n selections with replacement, so repeated items are allowed and k may exceed the input length. sample(sequence, k=n) chooses distinct positions without replacement. Its result is a new list; it does not shorten the input.

from random import Random

rng = Random(8)
print(rng.choice(["tea"]))
print(rng.choices(["tea"], k=3))
population = ["Ada", "Bo", "Cy", "Di"]
picked = rng.sample(population, k=3)
print(len(picked), len(set(picked)))
print(population)

# ✅ Expected output:
# tea
# ['tea', 'tea', 'tea']
# 3 3
# ['Ada', 'Bo', 'Cy', 'Di']
from random import Random

rng = Random(8)
rng.choice([])

# ✅ Expected error:
# IndexError: Cannot choose from an empty sequence

Decide what an empty menu means before calling choice: report no available items, or return a deliberate fallback. Do not keep retrying the same empty input. Sampling too many positions is a different mistake:

from random import Random

rng = Random(8)
rng.sample(["Ada", "Bo"], k=3)

# ✅ Expected error:
# ValueError: Sample larger than population or is negative

Reduce the sample size or deliberately switch to choices if repeats are allowed by the task. Do not silently switch algorithms merely to suppress the exception. Also, distinct positions are not necessarily distinct values:

from random import Random

rng = Random(9)
picked = rng.sample(["red", "red", "blue"], k=3)
print(sorted(picked))
print(len(picked), len(set(picked)))

# ✅ Expected output:
# ['blue', 'red', 'red']
# 3 2

There are two separate red entries to select. If a task requires distinct values, define how to deduplicate the population first. Do not pass a set directly: sample expects a sequence, and an unordered population also undermines reproducibility.

Shuffle changes the list and returns None

A shuffle rearranges the list you give it. Assigning its return value to the variable loses your reference to that list. Copy first when the original order must remain available, then call shuffle on its own line.

from random import Random

rng = Random(5)
original = ["Ada", "Bo", "Cy", "Di"]
shuffled = original.copy()
result = rng.shuffle(shuffled)
print(result)
print(original)
print(sorted(shuffled) == sorted(original))
print(shuffled is original)

# ✅ Expected output:
# None
# ['Ada', 'Bo', 'Cy', 'Di']
# True
# False

The final membership comparison checks that the same items remain, not that the order definitely changed. A valid random shuffle can leave a list in its original order. Tests that require every shuffle to differ will sometimes reject correct behaviour.

Copying versus aliasing is taught in Lists and Collections. Here a shallow copy is sufficient because shuffling rearranges references without mutating the people's names.

Weights change likelihood, not guaranteed quotas

choices() accepts relative weights. Weights of 1 and 3 make the second item more likely on each draw; they do not promise exactly three occurrences in every four draws. Weights must be nonnegative and finite, with at least one positive value, and there must be one weight per population item.

from random import Random

rng = Random(12)
picked = rng.choices(["closed", "open"], weights=[0, 1], k=4)
print(picked)

# ✅ Expected output:
# ['open', 'open', 'open', 'open']

If a classroom activity requires exactly two people in each team, construct those groups from a shuffled roster. Weighted independent draws do not enforce team sizes.

Keep simulation randomness away from security tokens

A fixed seed is useful for debugging and teaching, but makes the sequence reproducible by anyone who knows it. The random module is not suitable for passwords, password-reset links or other secrets. Use the secrets module for security-sensitive random values. No secret is generated or printed by this lesson.

Passing a generator into a function makes its random state explicit. Callers can give a reproducible generator in tests and a separately initialized generator in a simulation. An extra draw still changes what later calls receive; changing the order of operations changes the experiment.

Complete a shuffle that keeps the roster

Create an independent generator, copy the roster and shuffle the copy. Print the original plus a check that every person is still present; do not require the shuffled order to differ.

from random import Random

roster = ["Ada", "Bo", "Cy", "Di"]
rng = ___(10)
# 👉 replace ___ with Random
working = roster.___()
# 👉 replace ___ with copy
rng.___(working)
# 👉 replace ___ with shuffle
print(roster)
print(sorted(working) == sorted(roster))

# ✅ Expected output:
# ['Ada', 'Bo', 'Cy', 'Di']
# True

Deal two reproducible teams without losing anybody

Write make_teams(roster, seed). Copy the six-name roster, shuffle it using its own Random(seed), then return the first three names and the remaining three. Call the function twice with the same seed. Print whether the complete results match, both team sizes, whether the teams share any names, and whether their combined sorted names match the original. Use unique names and leave the input unchanged.

from random import Random

def make_teams(roster, seed):
    shuffled = roster.copy()
    Random(seed).shuffle(shuffled)
    return shuffled[:3], shuffled[3:]

roster = ["Ada", "Bo", "Cy", "Di", "Eli", "Fay"]
first = make_teams(roster, 21)
second = make_teams(roster, 21)
left, right = first
print(first == second)
print(len(left), len(right))
print(bool(set(left) & set(right)))
print(sorted(left + right) == sorted(roster))
print(roster)

# ✅ Expected output:
# True
# 3 3
# False
# True
# ['Ada', 'Bo', 'Cy', 'Di', 'Eli', 'Fay']

These checks separate four promises: replay, group sizes, no duplicated person and no lost person. They do not claim that one particular team is more random than another. The fixed fixture is exactly six unique names; a reusable application should validate that contract before dealing.

Practice quiz

What does this program print? from random import Random print(Random(2).randint(4, 4))

  • 3
  • 4
  • 5
  • ValueError

Answer: 4. randint includes both endpoints, which can be the same integer.

What does this program print? from random import Random print(Random(2).choices(["x"], k=3))

  • ['x']
  • []
  • ValueError
  • ['x', 'x', 'x']

Answer: ['x', 'x', 'x']. choices samples with replacement and can choose the sole item repeatedly.

What does this program print? from random import Random values = [1, 2, 3] print(Random(2).shuffle(values))

  • None
  • [1, 2, 3]
  • True
  • 3

Answer: None. shuffle mutates the list and returns None.

What does this program print? from random import Random a = Random(3) b = Random(3) print(a.random() == b.random())

  • False
  • 3
  • True
  • TypeError

Answer: True. Separate generators with the same seed begin with the same draw.

What does this program print? from random import Random print(len(set(Random(3).sample(["a", "a"], k=2))))

  • 0
  • 1
  • 2
  • ValueError

Answer: 1. Both positions are sampled, but their values are equal.

What does this program print? from random import Random rng = Random(3) print(all(x < 6 for x in [rng.randrange(1, 6) for _ in range(20)]))

  • False
  • 6
  • ValueError
  • True

Answer: True. randrange excludes its stop, regardless of which allowed values are drawn.

Which test is valid for a shuffle of a list of unique names?

  • The sorted result has the same names as the sorted input.
  • The order must change every time.
  • The first name must move.
  • Two calls must produce different results.

Answer: The sorted result has the same names as the sorted input.. A valid shuffle preserves all items and can sometimes produce the original order.

You need a password-reset token. Which module fits that purpose?

  • random with a fixed seed.
  • random with no recorded seed.
  • secrets.
  • A shuffled username.

Answer: secrets.. The random module is for simulation, not security-sensitive secrets.

Continue this course

Related lessons