Sub topic 5
The In-Place Fisher-Yates Shuffle
This chapter assumes you can read Python, are comfortable with zero-based array indexing, and know how to swap two list elements. It also builds on two earlier chapters: the definition of a fair shuffle (every one of the n! orderings has probability 1/n!) and the original 1938 pencil-and-paper method. Later chapters prove that the algorithm is uniform, measure its cost, and look at the off-by-one mistakes people make with it. This chapter covers how the algorithm works and how to write it correctly.
From Striking Out Numbers to Swapping
The original Fisher-Yates method works on paper. You write the items in a row, pick one of the items not yet struck out, copy it onto a new list, and strike it out. You repeat until nothing is left. The method is fair. On a computer, though, it is awkward for two reasons:
- Finding "the k-th item not yet struck out" means scanning past the struck-out ones, which costs O(n) per step and O(n²) overall.
- The method builds a second list, so it needs O(n) extra memory.
In 1964 Richard Durstenfeld published a version (Algorithm 235 in Communications of the ACM) that removes both problems with one change. Instead of striking out the chosen item, you swap it to the end of the region you have not yet processed. Every unprocessed item then stays packed together at the front of the array, and every finished item sits at the back. Choosing "the k-th remaining item" turns into reading an array index. Donald Knuth later spread this version widely as Algorithm P in The Art of Computer Programming, so you will see it called Fisher-Yates, Knuth shuffle, or Durstenfeld shuffle. All three names refer to the same procedure.
The Algorithm
Take an array of length n. Walk an index i from the last position, n − 1, down to 1. At each step:
- Choose
juniformly at random from the integers 0 throughi, includingiitself. - Swap
items[i]anditems[j].
After the swap, position i holds its final value and is never touched again. Positions 0 through i − 1 are the pool you still draw from.
import random
def fisher_yates(items):
for i in range(len(items) - 1, 0, -1):
j = random.randint(0, i) # inclusive on both ends: 0 <= j <= i
items[i], items[j] = items[j], items[i]
return items
print(fisher_yates(list(range(10))))Python's random.randint(a, b) includes both endpoints. Other languages usually give a half-open range, so the same step is written randrange(i + 1) in Python, rng.nextInt(i + 1) in Java, or Math.floor(Math.random() * (i + 1)) in JavaScript. The + 1 is required. Without it, j can never equal i, and you get a different algorithm, which a later chapter covers.
The Two Regions
At any moment the array splits into two parts:
| Region | Indices | Contents |
|---|---|---|
| Unshuffled pool | 0 to i | Items not yet placed, in no meaningful order |
| Finished tail | i + 1 to n − 1 | Items already placed in their final positions |
Each iteration moves the boundary one place to the left. It picks one item from the pool, uniformly at random, and puts it at the front edge of the tail. This is the original paper method rearranged. "Pick a remaining item at random" becomes j, and "write it on the output list" becomes the swap into position i. The output list is the tail, and it grows from right to left inside the same array.
When i reaches 0, the pool holds one item, so there is nothing left to choose and the loop can stop. That explains why the loop bound is 0 (exclusive) and not -1. Running one more iteration with i = 0 would always choose j = 0 and swap the element with itself. The result would still be correct, but the step does no work.
A Worked Trace
You can watch the regions change by supplying the random choices yourself instead of drawing them. The helper below takes a list of j values, one for each iteration, checks that each value is in range, and prints the array after every swap.
def fisher_yates_trace(items, choices):
steps = list(range(len(items) - 1, 0, -1))
if len(choices) != len(steps):
raise ValueError(f"need {len(steps)} choices, got {len(choices)}")
print("start ", items)
for i, j in zip(steps, choices):
if not 0 <= j <= i:
raise ValueError(f"j={j} is out of range for i={i}")
items[i], items[j] = items[j], items[i]
print(f"i={i}, j={j} ", items, "| final:", items[i:])
return items
fisher_yates_trace(["A", "B", "C", "D"], [1, 2, 0])Output:
start ['A', 'B', 'C', 'D']
i=3, j=1 ['A', 'D', 'C', 'B'] | final: ['B']
i=2, j=2 ['A', 'D', 'C', 'B'] | final: ['C', 'B']
i=1, j=0 ['D', 'A', 'C', 'B'] | final: ['A', 'C', 'B']Each step works like this:
- i = 3, j = 1. The pool is A B C D.
Bis chosen and swapped into the last slot.D, which was sitting there, moves into the holeBleft behind, so the pool stays contiguous. - i = 2, j = 2. The item already at position 2 (
C) is chosen. The swap does nothing, andCstays where it is. This self-swap is a legitimate outcome. Without it,Ccould never end up at index 2. - i = 1, j = 0. The pool is A D.
Ais chosen and moves to index 1.Dis the only item left and takes index 0.
The final order is D A C B.
The choices available are 4 at the first step, 3 at the second, and 2 at the third, so there are 4 × 3 × 2 = 24 possible choice sequences. That matches 4! = 24 permutations. The next chapter proves that each sequence gives a different permutation, which makes every permutation exactly 1/24 likely. For now, note how this differs from the naive shuffle covered earlier. There, every step had n choices, giving nⁿ sequences that cannot divide evenly among n! outcomes.
The Forward Variant
Nothing forces the loop to run backward. You can grow the finished region from the left instead: at step i, choose j from i through n − 1 and swap it into position i.
import random
def fisher_yates_forward(items):
n = len(items)
for i in range(n - 1):
j = random.randint(i, n - 1) # inclusive: i <= j <= n - 1
items[i], items[j] = items[j], items[i]
return items
print(fisher_yates_forward(list("ABCDEFGH")))Here the pool is indices i to n − 1 and the finished region is 0 to i − 1. Both directions are uniform. The forward form has one practical advantage: if you stop after k steps, the first k slots already hold a uniformly random ordered sample. A later chapter on partial shuffles builds on this. The backward form is the one you will see most often in textbooks and libraries, because the range 0..i fits the half-open randrange(i + 1) idiom neatly.
Edge Cases and Practical Gotchas
Empty and single-element lists. With n = 0, range(-1, 0, -1) is empty. With n = 1, range(0, 0, -1) is also empty. Both return the input unchanged, which is the only possible permutation in each case. No special case is needed.
Duplicate values. The algorithm shuffles positions, not values. [1, 1, 2] still goes through 3! = 6 equally likely position arrangements, but only 3 of them look different. [1, 1, 2], [1, 2, 1] and [2, 1, 1] each appear with probability 1/3. This is correct behaviour, and you need to remember it when testing a shuffle by counting outputs.
Mutation and immutable input. The function rearranges its argument in place. Strings and tuples cannot be modified, so you have to copy them first:
word = "shuffle"
letters = list(word)
fisher_yates(letters)
print("".join(letters))Python slices are copies. fisher_yates(deck[10:20]) shuffles a new list and leaves deck unchanged. To shuffle part of a list in place, either assign the result back (deck[10:20] = fisher_yates(deck[10:20])) or pass lo and hi bounds and loop over that range.
Return value convention. The version here returns the list so it can be used in a single expression. Python's built-in random.shuffle returns None on purpose, so you don't mistake it for a function that makes a copy. If you write deck = random.shuffle(deck), deck becomes None.
The random source still matters. The algorithm is uniform only if each j is uniform on its range. If you compute j with something like rand() % (i + 1) from a generator with a small range, a small bias comes back in through the index draws. That problem and its fix are covered in the chapters on unbiased random indices and generator state size.
Exercise
Run the backward in-place shuffle by hand on ["P", "Q", "R", "S", "T"] with the choices j = 0, 3, 1, 1 (for i = 4, 3, 2, 1 respectively). What is the final array, and which choice was a self-swap?
Show answer
i=4, j=0 swaps P and T: [T, Q, R, S, P]. i=3, j=3 is a self-swap: [T, Q, R, S, P]. i=2, j=1 swaps Q and R: [T, R, Q, S, P]. i=1, j=1 is a self-swap: [T, R, Q, S, P]. The final array is [T, R, Q, S, P]. The choices at i=3 and i=1 were self-swaps.
Exercise
How many distinct choice sequences does the backward loop produce for an array of length 6, and why does the loop not need an iteration for i = 0?
Show answer
There are 6 × 5 × 4 × 3 × 2 = 720 sequences, which equals 6!. At i = 0 the pool holds only index 0, so the only possible choice is j = 0. That swap does nothing, so skipping it changes neither the result nor the probabilities.
Exercise
A colleague writes the forward variant as for i in range(n - 1): j = random.randint(i + 1, n - 1). What is wrong, and what is the fix?
Show answer
The range leaves out j = i, so the item at position i can never stay there. That removes valid outcomes and breaks uniformity. The fix is j = random.randint(i, n - 1), which includes i.