Sub topic 14
The Inside-Out Variant
This chapter assumes you know the in-place Fisher-Yates shuffle from earlier chapters, the induction argument used to prove it uniform, and how to count permutation frequencies to test a shuffle. The code is Python.
The in-place shuffle has one practical limit: it rearranges the list you hand it. Sometimes that is not allowed. The caller may still need the original order, or the data may not be a list at all. It could be a generator, a file read line by line, or a network stream whose length you don't know in advance. The inside-out variant handles these cases. It reads the source once, from front to back, and builds a new shuffled list as it goes.
How the Algorithm Works
The idea is to keep a result list that is always a uniformly shuffled copy of everything read so far. When a new item x arrives at position i, the algorithm picks a random slot j from 0 to i inclusive. Then it does one of two things:
- If
j == i, it appendsxto the end. The new item stays where it arrived. - Otherwise, it moves the current occupant of slot
jto the end of the list and putsxinto slotj.
Either way the list grows by one, and each element moves at most once per step.
import random
def inside_out_shuffle(source):
result = []
for i, x in enumerate(source):
j = random.randint(0, i) # inclusive: 0 <= j <= i
if j == i:
result.append(x)
else:
result.append(result[j])
result[j] = x
return result
original = ["A", "B", "C", "D", "E"]
shuffled = inside_out_shuffle(original)
print(original) # unchanged
print(shuffled) # a uniformly random ordering of the same itemsThe j == i branch is needed in Python. When j == i, result[j] does not exist yet, because the list has only i elements at that point. Reading it would raise an IndexError.
A Worked Trace
Shuffle the stream A, B, C, D with these random draws: j = 0, 0, 1, 3.
| i | x | j | Action | result after step |
|---|---|---|---|---|
| 0 | A | 0 | j == i, append A | [A] |
| 1 | B | 0 | move A to end, put B at 0 | [B, A] |
| 2 | C | 1 | move A to end, put C at 1 | [B, C, A] |
| 3 | D | 3 | j == i, append D | [B, C, A, D] |
The first draw is always j = 0, because randint(0, 0) has only one possible value. This matches the in-place version, where the last loop iteration is skipped because it has no real choice to make.
Why It Is Uniform
The proof is an induction on the number of items read, and it follows the same pattern as the proof for the in-place version.
Claim. After reading k items, result is each of the k! orderings of those items with probability 1/k!.
Base case. After one item, result is [x0]. There is 1! = 1 ordering, and it occurs with probability 1.
Inductive step. Assume the claim holds after k items. Item x arrives with i = k, and j is drawn uniformly from k + 1 values. Each pair (previous ordering, j) produces exactly one new ordering of k + 1 items. The mapping also runs backwards without ambiguity. Given any ordering of the k + 1 items, you can find where x sits. That position is j. If j is not the last slot, the item in the last slot is the one that was displaced, so you put it back at j to recover the previous ordering. Because the mapping is a bijection between k! × (k + 1) pairs and (k + 1)! orderings, each new ordering has probability:
(1 / k!) × (1 / (k + 1)) = 1 / (k + 1)!This is the reason the bound on j must include i. If you drop that one value, the counting no longer matches up.
Relation to the In-Place Version
Copying a list and then shuffling the copy in place also leaves the original untouched. So why bother with a separate variant? The table compares the options.
| Approach | Reads source | Needs length up front | Extra memory | Writes to source |
|---|---|---|---|---|
| In-place Durstenfeld | random access | yes | O(1) | yes |
| Copy, then Durstenfeld | once to copy, then random access on the copy | yes, once copied | O(n) | no |
| Inside-out | once, sequentially | no | O(n) (the output) | no |
For a list you already have in memory, copy-then-shuffle and inside-out cost about the same. Both take O(n) time and use one output list. Inside-out wins in two situations. The first is when the input is an iterator that you can only read once and whose length is unknown. The second is when you want to fill the output in a single pass, for example while also transforming each element:
import random
def shuffled_squares(numbers):
result = []
for i, n in enumerate(numbers):
x = n * n
j = random.randint(0, i)
if j == i:
result.append(x)
else:
result.append(result[j])
result[j] = x
return result
# Works on a generator: no len(), no second pass.
print(shuffled_squares(n for n in range(10)))The same idea explains why the variant handles empty input without special cases. With no items, the loop body never runs and the function returns []. With one item, the result is just that item.
Common Mistakes
Overwriting before saving
Writing the assignment first loses data:
# Wrong: result[j] is overwritten before it is copied to the end.
result[j] = x
result.append(result[j]) # appends x a second time; the old item is goneThe output then contains duplicates and is missing items. A test that checks sorted(output) == sorted(input) catches this right away.
Using insert at a random position
This version is tempting:
import random
def insert_shuffle(source):
result = []
for i, x in enumerate(source):
result.insert(random.randint(0, i), x)
return resultThis version is actually uniform. Each of the i + 1 insertion points is equally likely, and the same bijection argument applies. The problem is speed. list.insert shifts every later element, so the total cost is O(n²). For a million items that is around 10¹¹ element moves where inside-out needs about 10⁶. Correctness tests will pass and the code will still be too slow, so check performance separately.
Always swapping, even when j equals i
In languages where you can pre-size the output array, a common simplification is:
import random
def inside_out_presized(source):
source = list(source)
n = len(source)
result = [None] * n
for i in range(n):
j = random.randint(0, i)
result[i] = result[j] # when j == i this copies None into itself, harmless
result[j] = source[i]
return resultThis is correct. When j == i, the first line copies a placeholder onto itself and the second line overwrites it with the real item. You can drop the branch only because the slot already exists. In the append-based version the slot does not exist yet, so the branch stays.
Checking It Empirically
Use the frequency-count approach from the testing chapter. With 60,000 trials on three items, each of the six orderings should appear about 10,000 times.
import random
from collections import Counter
def inside_out_shuffle(source):
result = []
for i, x in enumerate(source):
j = random.randint(0, i)
if j == i:
result.append(x)
else:
result.append(result[j])
result[j] = x
return result
counts = Counter(tuple(inside_out_shuffle([1, 2, 3])) for _ in range(60000))
for perm, c in sorted(counts.items()):
print(perm, c)
print("distinct orderings:", len(counts)) # expect 6If you change the draw to random.randrange(i) and rerun, only two orderings appear: (2, 3, 1) and (3, 1, 2). These are the two 3-cycles, and the other four orderings never come up.
Exercise
Trace insideoutshuffle on the stream W, X, Y, Z with random draws j = 0, 1, 0, 2. What is the final result?
Show answer
i=0: append W -> [W]. i=1, j=1 == i: append X -> [W, X]. i=2, j=0: move W to the end, put Y at 0 -> [Y, X, W]. i=3, j=2: move W to the end, put Z at 2 -> [Y, X, Z, W].
Exercise
A colleague says inside-out is pointless because shuffled = items.copy(); random.shuffle(shuffled) does the same job. When is the colleague right, and when does inside-out give a real advantage?
Show answer
The colleague is right when the input is already a list in memory. Both approaches take O(n) time and O(n) output memory, and the library call is simpler and well tested. Inside-out helps when the input is a one-pass iterator or stream of unknown length, which random.shuffle cannot take directly, or when you want to transform and shuffle in a single pass without building an intermediate list.
Exercise
Why is result.insert(random.randint(0, i), x) a correct but poor implementation of a shuffle, and what test would reveal the problem?
Show answer
It is uniform, because each of the i + 1 insertion points is equally likely, which gives a bijection onto orderings of i + 1 items. But each insert shifts up to i elements, so the total time is O(n^2). A frequency-count test passes. Only a timing test on large inputs, for example comparing 10^5 and 10^6 items, shows the time growing roughly 100 times when the input grows 10 times.