Sub topic 7
Picking, sampling, and shuffling sequences
This chapter assumes you can use lists, indexes, and import, and that you have met random.randint and random.Random(seed). Here you will use four functions that work on whole sequences: choice, sample, choices, and shuffle.
Choosing the right function
Each function answers a different question about a list.
| Function | Returns | Repeats possible? | Changes the list? |
|---|---|---|---|
| `choice(seq)` | one item | not applicable | no |
| `sample(seq, k)` | list of `k` items | no | no |
| `choices(seq, k=n)` | list of `n` items | yes | no |
| `shuffle(seq)` | `None` | not applicable | yes, in place |
All four in action
import random
rng = random.Random(1)
items = ["A", "B", "C", "D", "E"]
print(rng.choice(items)) # one item
print(rng.sample(items, k=2)) # two distinct items
print(rng.choices(items, weights=[5, 1, 1, 1, 1], k=3)) # repeats allowed, weighted
rng.shuffle(items) # reorders the list in place
print(items)The seed makes the output repeatable on the same Python version, so this is a good pattern for code you want to test.
Sampling versus choices
sample draws without replacement. Once an item is picked, it cannot be picked again, so the result never contains duplicates. This fits a lottery draw or a random team selection. Because of this, k cannot be larger than the sequence.
choices draws with replacement. Each pick is independent, so the same item can appear many times. It also accepts weights, which are relative likelihoods and do not need to add up to 1. In the example above, "A" is five times as likely as any other letter on each pick.
sample also accepts a counts argument for populations with repeated values. For example, rng.sample(["red", "blue"], counts=[3, 2], k=2) treats the population as three reds and two blues.
Shuffle changes the list and returns nothing
shuffle reorders the list you give it and returns None. This is the most common mistake with these functions. If you keep the return value, you lose your data.
import random
rng = random.Random(3)
cards = [1, 2, 3, 4, 5]
wrong = rng.shuffle(cards)
print(wrong) # None
right = rng.sample(cards, k=len(cards)) # a new shuffled list
print(right)
print(cards) # the original is untouched by sampleUse sample(seq, k=len(seq)) when you need a shuffled copy and want to keep the original order. Because shuffle modifies its argument, it fails on tuples and strings, which cannot be changed. Convert to a list first with list(text).
Common errors
import random
rng = random.Random(0)
for action in (
lambda: rng.choice([]), # empty sequence
lambda: rng.sample([1, 2, 3], 5), # k larger than the population
lambda: rng.shuffle((1, 2, 3)), # tuples are immutable
lambda: rng.sample({1, 2, 3}, 2), # sets are not sequences
):
try:
action()
except (IndexError, ValueError, TypeError) as exc:
print(type(exc).__name__)This prints IndexError, ValueError, TypeError, TypeError. In each case the fix is to give the function a non-empty sequence of the right type and size. For a set, convert it first with sorted(my_set) or list(my_set).
Practice
Exercise
You have a list names of 10 people. You need to pick 3 different winners, and you must still have the original list in its original order afterward. Which function do you use, and why not shuffle?
Show answer
Use rng.sample(names, k=3). It returns 3 distinct names and leaves names unchanged. shuffle would reorder names in place, so the original order would be lost, and you would still need to slice the first 3 items.
Exercise
A game drops loot with these odds: "common" is five times as likely as "rare". Write the call that produces 4 drops from ["common", "rare"] using a Random instance named rng. Can the same item appear twice?
Show answer
rng.choices(["common", "rare"], weights=[5, 1], k=4). Yes, repeats can appear, because choices draws with replacement.