Sub topic 13
Partial Shuffles: Picking k Random Items
You often need only a few random items from a list, not a full shuffle: 5 cards from a deck, 10 survey participants from a user table, 3 questions from a question bank. This chapter shows how to stop Fisher-Yates early so it returns a uniformly random sample of k items. You do only k steps of work instead of n.
The chapter assumes you already know the in-place Fisher-Yates loop, its uniformity proof, and why the random index range must be exactly right. You should also be comfortable reading Python and doing basic counting with factorials.
The Idea: Fisher-Yates Builds the Result One Slot at a Time
The forward form of Fisher-Yates walks i from 0 upward. At step i it picks j uniformly from positions i through n − 1 and swaps items[i] with items[j]. After that swap, position i holds its final value, and the loop never touches it again. So the prefix items[0..i] grows by one settled element at each step.
If you only need k items, you can stop once the first k positions are settled. The rest of the array is left in some scrambled state, but you never look at it.
import random
def sample_k(items, k):
n = len(items)
for i in range(k):
j = random.randint(i, n - 1)
items[i], items[j] = items[j], items[i]
return items[:k]
deck = list(range(52))
hand = sample_k(deck, 5)
print(hand)Each run prints five distinct numbers from 0 to 51 in random order.
Why the Sample Is Uniform
An ordered sample of k items from n distinct items is a k-permutation. There are
n × (n − 1) × … × (n − k + 1) = n! / (n − k)!
of them. A fair sampler must return each one with probability (n − k)! / n!.
The argument follows the full-shuffle proof, cut short. At step 0, each of the n items has a 1/n chance of landing in slot 0. At step 1, the remaining n − 1 unsettled items sit in positions 1 through n − 1, and each has a 1/(n − 1) chance of landing in slot 1. This continues for k steps. For any specific ordered k-tuple, the probability of producing it is
1/n × 1/(n − 1) × … × 1/(n − k + 1) = (n − k)! / n!
That is exactly the uniform probability. The same result also follows without algebra. A full shuffle is uniform over all n! orderings, and its first k slots are decided entirely by its first k steps. Stopping after those steps therefore gives you the same distribution over prefixes that a full shuffle would.
Two useful consequences follow:
- The sample is uniform as an ordered sequence. If you only care about which items were chosen, the unordered set is also uniform over all C(n, k) subsets, because each subset corresponds to the same number of orderings, k!.
- With k = n − 1 you already get a complete uniform shuffle. The last slot has only one candidate left, so step n − 1 never has a choice to make. This is why the full loop can stop one step early.
The Backward Form
Durstenfeld's loop usually runs from the end. It settles the suffix instead of the prefix, so the partial version returns the last k items:
import random
def sample_k_backward(items, k):
n = len(items)
for i in range(n - 1, n - 1 - k, -1):
j = random.randint(0, i)
items[i], items[j] = items[j], items[i]
return items[n - k:]Both forms are equally correct. Pick the one that matches the full shuffle already in your codebase, so a reader can see that the partial version is the same loop with an earlier stop.
Cost
| Approach | Random draws | Swaps | Extra memory | Modifies input |
|---|---|---|---|---|
| Full shuffle, then slice | n − 1 | n − 1 | O(1) or O(k) for the slice | yes |
| Partial shuffle on the list | k | k | O(k) for the result | yes |
| Partial shuffle on a copy | k | k | O(n) for the copy | no |
| Sparse partial shuffle (below) | k | k map updates | O(k) | no input list needed |
The partial shuffle does O(k) work only if the array already exists and you are allowed to change it. If you have to copy the input first to protect the caller's list, the copy costs O(n), which removes most of the savings when k is small.
Reusing the Same Array for Repeated Samples
Suppose you deal many independent hands from one deck. You do not need to restore the deck between calls. The uniformity proof never assumed a particular starting order: the result is uniform for any starting arrangement of distinct items. A deck left scrambled by the previous call is a perfectly valid input for the next one, so repeated calls on the same list each cost only O(k).
Sampling From a Huge Range Without the Array
Sometimes the "items" are just the integers 0 through n − 1, and n is huge, say 10⁹ user IDs. You cannot afford a billion-element list just to pick 10 of them. You can simulate the array with a dictionary that records only the positions that have been swapped. Any position missing from the dictionary still holds its own index.
import random
def sample_range_sparse(n, k):
"""Uniform ordered sample of k distinct integers from range(n)."""
if not 0 <= k <= n:
raise ValueError("need 0 <= k <= n")
moved = {} # position -> value, only for positions that changed
result = []
for i in range(k):
j = random.randint(i, n - 1)
value_i = moved.get(i, i)
value_j = moved.get(j, j)
moved[j] = value_i # slot j now holds what was at i
moved.pop(i, None) # slot i is settled and never read again
result.append(value_j) # slot i's final value
return result
print(sample_range_sparse(10**9, 10))Each step adds at most one entry to the dictionary, so memory and time are both O(k), however large n is. The random draws are the same ones the array version would make, so the output distribution is identical.
Edge Cases
- k = 0 returns an empty list and draws no random numbers.
- k = n is a full shuffle with one wasted draw at the end.
randint(n - 1, n - 1)always returns n − 1. - k > n has no valid answer. The slice in
sample_khides this:items[:k]just returns all n items, and the loop crashes with aValueErrorfromrandintonce i exceeds n − 1. Validate k explicitly, assample_range_sparsedoes. - Duplicate values in the input are fine. The algorithm samples positions, so the result is a uniform sample of positions, and a value that appears twice can be picked twice.
- Wrong range. Writing
random.randint(0, n - 1)inside the forward loop reintroduces the naive-shuffle bias, and already-settled items can be pulled back out of the prefix. The lower bound must be i.
Checking the Sampler Empirically
For n = 4 and k = 2 there are 4 × 3 = 12 ordered samples, so each should appear in about 1/12 of the trials.
import random
from collections import Counter
def sample_k(items, k):
n = len(items)
for i in range(k):
j = random.randint(i, n - 1)
items[i], items[j] = items[j], items[i]
return items[:k]
trials = 120000
counts = Counter(tuple(sample_k([0, 1, 2, 3], 2)) for _ in range(trials))
expected = trials / 12
chi_square = sum((c - expected) ** 2 / expected for c in counts.values())
for outcome, c in sorted(counts.items()):
print(outcome, c)
print("outcomes:", len(counts), "chi-square:", round(chi_square, 2))You should see 12 outcomes, each near 10,000. With 11 degrees of freedom, a chi-square value above about 19.7 would be suspicious at the 5% level. Change the lower bound to 0 and rerun to watch the statistic climb.
Exercise
How many distinct ordered results can sample_k produce for n = 5 and k = 2, and with what probability does each occur?
Show answer
5 × 4 = 20 ordered results, each with probability 1/20. That is (n − k)!/n! = 3!/5! = 6/120.
Exercise
A colleague writes the forward partial shuffle with j = random.randint(0, n - 1). Explain what goes wrong.
Show answer
Slots 0..i−1 are supposed to be settled, but this range lets step i swap one of them back out. Settled items can leave the sample, and the procedure turns into a truncated naive shuffle. Its n^k equally likely draw sequences cannot be divided evenly across the n!/(n−k)! ordered samples in general, so some samples are more likely than others. The lower bound must be i.
Exercise
You need 20 distinct random IDs from range(2**40) and cannot allocate a list of that size. Which technique fits, and what are its time and memory costs?
Show answer
The sparse partial shuffle, which keeps a dictionary of moved positions. Alternatively, use random.sample(range(2**40), 20). The sparse shuffle does 20 random draws and at most 20 dictionary entries, so it runs in O(k) time and O(k) memory, independent of n.
Exercise
Why can you call sample_k repeatedly on the same deck without restoring it to sorted order between calls?
Show answer
Fisher-Yates is uniform for any starting arrangement of distinct items. The proof never depends on the initial order. A deck left scrambled by the previous call is therefore as good an input as a sorted one, and each new sample is uniform and independent, given an independent random source.