Sub topic 7
Picking, Sampling, and Shuffling Sequences
This chapter assumes you can write Python functions and loops, work with lists and strings, and have met random.random() and random.randint(). The functions here take a whole sequence and make a random decision about its items. The details that cause bugs are replacement, ordering, mutation, and what happens at the edges.
The four tools at a glance
The random module has four functions for working with sequences. They differ in three ways: whether the same item can come back, whether the input is changed, and what they return.
| Function | Returns | Repeats possible | Changes the input |
|---|---|---|---|
| `choice(seq)` | One item | Not applicable | No |
| `sample(pop, k)` | List of `k` items | No | No |
| `choices(pop, k=...)` | List of `k` items | Yes | No |
| `shuffle(lst)` | `None` | Not applicable | Yes, in place |
The examples below use a random.Random instance called rng. The module-level functions (random.choice and so on) behave the same way. They share one hidden instance, which is why you can seed them with random.seed().
Picking one item with choice
choice returns one element from a non-empty sequence. The sequence must support len() and indexing, so lists, tuples, strings, and ranges all work.
import random
rng = random.Random(1)
colors = ["red", "green", "blue"]
print(rng.choice(colors) in colors) # True
print(rng.choice("abc") in "abc") # True: a string is a sequence of characters
print(rng.choice(range(10, 20)) in range(10, 20)) # True
try:
rng.choice([])
except IndexError as exc:
print("Empty sequence:", type(exc).__name__)An empty sequence raises IndexError. If the list comes from user input or a filter, check it first or catch the error.
Sets and dictionaries are not sequences, so choice rejects them. Convert first:
import random
rng = random.Random(1)
tags = {"python", "math", "dates"}
try:
rng.choice(tags)
except TypeError as exc:
print("Sets are not indexable:", type(exc).__name__)
print(rng.choice(sorted(tags)) in tags) # TrueSorting before choosing matters if you also seed the generator. Set order can vary between runs for strings, so list(tags) could give a different order each time and break reproducibility. sorted(tags) gives a stable order.
Sampling without replacement
sample(population, k) returns a new list of k items with no repeated positions. It is the right tool for dealing cards, picking winners, or taking a test subset.
import random
rng = random.Random(1)
items = ["A", "B", "C", "D", "E"]
picked = rng.sample(items, k=3)
print(len(picked), len(set(picked))) # 3 3
print(items) # ['A', 'B', 'C', 'D', 'E'] (unchanged)
try:
rng.sample(items, k=10)
except ValueError as exc:
print("k larger than population:", type(exc).__name__)Three behaviors are worth knowing:
- The original list is not modified, and the result is in random order. Selection order is part of the result, not just membership.
- "No repeats" means no repeated positions. If the population contains duplicate values, the same value can appear twice in the sample.
- Since Python 3.11 the population must be a sequence. Passing a set raises
TypeError. Before 3.11, sets were accepted with a deprecation warning.
If the population has duplicates because of counts, use the counts argument (Python 3.9 and later) instead of building a long list:
import random
rng = random.Random(5)
# Equivalent to a bag of 3 red, 2 blue, and 1 green marble
drawn = rng.sample(["red", "blue", "green"], counts=[3, 2, 1], k=4)
print(len(drawn)) # 4Sampling with replacement and weights
choices (plural) draws k items and puts each one back before the next draw. Items can repeat, and k can be larger than the population. The k argument is keyword-only, and the default is k=1. The result is always a list, even for k=1.
import random
from collections import Counter
rng = random.Random(3)
loot = ["common", "uncommon", "rare"]
counts = Counter(rng.choices(loot, weights=[70, 20, 10], k=1000))
print(sum(counts.values())) # 1000
print(counts["common"] > counts["rare"]) # TrueWeights are relative, so [70, 20, 10] and [7, 2, 1] mean the same thing. They need not sum to 1 or 100. Weights must be non-negative numbers, one per item. If the total is zero, Python 3.9 and later raise ValueError. You can pass cum_weights instead of weights if you already have cumulative totals, which skips a step when you draw many times from the same distribution. Passing both raises TypeError.
choices has no weighted version that avoids repeats. For small integer weights, sample with counts is one workaround. Otherwise, draw one item at a time with choices, remove it from the pool, and repeat.
Shuffling in place
shuffle reorders a mutable sequence in place and returns None. This is a frequent source of bugs.
import random
rng = random.Random(9)
deck = [1, 2, 3, 4, 5]
result = rng.shuffle(deck)
print(result) # None
print(sorted(deck)) # [1, 2, 3, 4, 5]: same items, new order
# Wrong: deck = rng.shuffle(deck) would set deck to None
t = (1, 2, 3)
try:
rng.shuffle(t)
except TypeError as exc:
print("Tuples cannot be shuffled in place:", type(exc).__name__)To get a shuffled copy and keep the original, sample the whole population:
import random
rng = random.Random(9)
original = ["x", "y", "z"]
shuffled = rng.sample(original, k=len(original))
print(original) # ['x', 'y', 'z']
print(sorted(shuffled)) # ['x', 'y', 'z']This also works for tuples and strings, since sample never mutates its input. For a string, "".join(rng.sample(word, k=len(word))) gives a shuffled string.
A shuffle of n items has n! possible orderings. Python's internal generator has a very large state, but for lists longer than about 2080 items the number of orderings exceeds the generator's period, so not every ordering is reachable. This never matters for games or tests, but it is a good reason not to use random for security.
Choosing the right function
The diagram summarizes the decisions.
Reproducibility and testing
Create your own random.Random(seed) instance when results must be repeatable. Two instances with the same seed produce the same sequence of calls, and an instance does not disturb other code that uses the global generator.
import random
def deal_hand(rng, deck, size=3):
return rng.sample(deck, k=size)
deck = ["A", "B", "C", "D", "E", "F"]
first = deal_hand(random.Random(42), deck)
second = deal_hand(random.Random(42), deck)
print(first == second) # TruePassing the generator as an argument, as deal_hand does, makes a function easy to test. Python guarantees that random() stays stable for a given seed across versions. Methods such as choice, sample, and shuffle can change their exact output between Python releases, so do not store expected outputs from one version and compare against another. Test properties instead: length, membership, and the absence of duplicates.
Common errors
- Using the return value of
shuffle. It isNone. Shuffle the list, then use the list. - Asking
samplefor too many items.kgreater than the population size raisesValueError. - Using
choicesfor distinct picks. It samples with replacement. - Passing a set or dict. Convert to a sorted list first.
- Shuffling a list you still need in order. Copy it first with
sampleorlist(...). - Mismatched weights. The weights list must be the same length as the population, or
ValueErroris raised.
Exercise
You need to pick 3 different winners from a list of 10 entrants, and the entrant list must stay in its original order afterward. Which function do you use, and what does random.shuffle(entrants) do wrong here?
Show answer
Use rng.sample(entrants, k=3). It returns three distinct entrants and leaves entrants unchanged. shuffle reorders the original list in place, which destroys its order, and it returns None, so you would still need to slice the first three items yourself.
Exercise
What does this code print, and why? import random, then rng = random.Random(0), then print(len(set(rng.choices([1, 2], k=5))) <= 2).
Show answer
It prints True. choices draws 5 items with replacement from only two values, so the set of results can contain at most two distinct values. This also shows that k may exceed the population size for choices, which would fail for sample.
Exercise
Write a function shuffled_copy(seq, rng) that returns a new list with the items of any sequence (including a tuple) in random order, without changing seq.
Show answer
def shuffled_copy(seq, rng): return rng.sample(seq, k=len(seq))