Randomness with the random Module

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.

Learn Randomness with the random Module in our free Python course — an interactive lesson with runnable examples, a practice exercise and a quick reference.

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.

Roll dice, deal cards, shuffle a playlist, or sample a dataset — it is one of the most fun and useful modules in the standard library. We will seed every example so your output matches exactly.

Three workhorses cover most needs: random() for a float in [0.0, 1.0) , uniform(a, b) for a float in any range, and randint(a, b) for a whole number with both ends included:

Calling seed() with a fixed value resets the generator to a known starting point, so re-running gives the identical sequence — invaluable for tests and debugging:

These three pick from a sequence in different ways. choice grabs one; choices grabs k items with replacement (repeats allowed); sample grabs k distinct items with no repeats:

Remember the rule: choices can repeat and accepts a weights= argument; sample never repeats. Asking sample for more items than exist raises a ValueError .

shuffle() rearranges a list in place — it changes the original list and returns None . It is perfect for shuffling a deck of cards or a playlist:

Complete the program so it seeds the generator and rolls a reproducible number. Replace each ___ and match the expected output.

First blank: seed — so the line is random.seed(0) .

Second blank: randint — so the line is random.randint(1, 100) , which yields 50 for seed 0.

✅ shuffle works in place — just call random.shuffle(deck) and keep using deck .

✅ Use secrets.choice(chars) or secrets.token_hex() for anything security-related.

✅ Keep k <= the length of the sequence, or use choices (which allows repeats).

Roll two dice many times and confirm that 7 is the most common total. Everything is seeded, so your numbers will match exactly.

Go deeper with the official Python documentation:

Lesson complete — you can generate randomness on demand!

You can produce floats and integers, pick items with choice , choices , and sample , shuffle a list in place, reproduce results with seed() , and you know to reach for secrets when security matters.

🚀 Up next: Running Commands with subprocess — call external programs from your Python code.

Practice quiz

What does calling random.seed() with a fixed value achieve?

  • Makes numbers more truly random
  • Speeds up generation
  • Makes the generated sequence reproducible on re-runs
  • Prevents repeats within a sequence

Answer: Makes the generated sequence reproducible on re-runs. Seeding with the same value resets the generator to a known start, so you get the identical sequence every run — invaluable for tests and debugging.

Which range does random.randint(1, 6) cover?

  • 1 to 6 (both ends inclusive)
  • 1 to 5 (top excluded)
  • 0 to 6
  • 2 to 6

Answer: 1 to 6 (both ends inclusive). Unlike range, randint(a, b) includes BOTH endpoints, so randint(1, 6) can return 1, 2, 3, 4, 5, or 6 — a perfect die.

What does random.random() return?

  • An integer from 0 to 1

random.random() returns a float in the half-open interval [0.0, 1.0) — 0.0 is possible but 1.0 is not.

How does random.choices() differ from random.sample()?

  • choices is without replacement; sample allows repeats
  • choices allows repeats (with replacement) and weights; sample never repeats
  • They are identical
  • sample only works on strings

Answer: choices allows repeats (with replacement) and weights; sample never repeats. choices() picks k items WITH replacement (repeats allowed, supports weights); sample() picks k DISTINCT items without replacement.

What does random.shuffle(deck) return?

  • None — it shuffles in place
  • A new shuffled list
  • The original list
  • A tuple

Answer: None — it shuffles in place. shuffle() rearranges the list in place and returns None, so never write deck = random.shuffle(deck).

How can you get a shuffled COPY without modifying the original list?

  • random.shuffle(copy)
  • random.choice(original)
  • random.sample(original, len(original))
  • random.random(original)

Answer: random.sample(original, len(original)). random.sample(seq, len(seq)) returns a new shuffled list while leaving the original untouched.

Why should you NOT use the random module for passwords or tokens?

  • It is too slow
  • Its Mersenne Twister output is predictable and can be reconstructed by an attacker
  • It only produces integers
  • It requires a network connection

Answer: Its Mersenne Twister output is predictable and can be reconstructed by an attacker. random uses the predictable Mersenne Twister; for anything security-sensitive use the secrets module, which draws from a cryptographically secure source.

What happens with random.sample([1, 2, 3], 5)?

  • Returns 5 items with repeats

sample cannot draw more distinct items than exist, so asking for 5 from a 3-element population raises ValueError. Use choices() if repeats are acceptable.

Which function gives a range-style exclusive top, never returning the upper bound?

  • random.randint(a, b)
  • random.randrange(a, b)
  • random.random()
  • random.choice(seq)

Answer: random.randrange(a, b). random.randrange(a, b) follows the range() convention and never returns b, unlike randint which is inclusive.

Which secrets function produces a secure random hex string suitable for a token?

  • random.token_hex(16)
  • secrets.random()
  • secrets.token_hex(16)
  • random.choice(chars)

Answer: secrets.token_hex(16). secrets.token_hex(16) returns a cryptographically secure random hex string — the right tool for tokens, unlike anything in random.