Sub topic 12
Using Your Language's Built-In Shuffle
This chapter assumes you know how Fisher-Yates works. It also builds on two earlier chapters: the one on drawing unbiased random indices and the one on random generators whose state is too small. You should be able to read short Python and to follow small Java, C++, Go, and JavaScript programs.
In production code, you should almost always use your language's built-in shuffle instead of writing your own. Most standard libraries implement Fisher-Yates and draw their indices without modulo bias. People who maintain the library have already checked the loop bounds. The common mistakes in this area come from using the library wrong: shuffling the wrong object, expecting a return value, seeding badly, or picking the wrong generator for the job.
What the Standard Libraries Provide
| Language | In-place shuffle | Notes |
|---|---|---|
| Python | `random.shuffle(x)` | Returns `None`. `random.sample(x, k=len(x))` gives a shuffled copy. |
| Java | `Collections.shuffle(list)` or `Collections.shuffle(list, rnd)` | Works on a `List`, not on a primitive array. |
| C++ | `std::shuffle(first, last, gen)` | `std::random_shuffle` was deprecated in C++14 and removed in C++17. |
| Go | `rand.Shuffle(n, swap)` | Takes a swap callback, so it works with any indexable data. |
| C# (.NET 8+) | `Random.Shared.Shuffle(array)` | `RandomNumberGenerator.Shuffle(span)` is the cryptographic version. |
| Rust | `slice.shuffle(&mut rng)` | Comes from the `rand` crate (`rand::seq::SliceRandom`), not from `std`. |
| Swift | `array.shuffle()` / `array.shuffled()` | `shuffled(using:)` accepts a custom generator. |
| JavaScript | None | Write Fisher-Yates yourself or use a vetted library such as Lodash's `_.shuffle`. |
All of these shuffle uniformly as long as the generator you give them is good. When one of them fails to be uniform, the cause is the generator, as the earlier chapter on generator state size explained.
Python in Detail
In place versus a copy
random.shuffle changes the list you pass in and returns None. A frequent bug is to assign its result:
import random
deck = list(range(10))
result = random.shuffle(deck)
print(result) # None: the shuffled data is in deck
print(deck)
original = list(range(10))
copy = random.sample(original, k=len(original))
print(original) # unchanged
print(copy) # a uniformly shuffled new listrandom.sample needs a sequence. Since Python 3.11 it rejects sets, because iterating over a set gives an order that is arbitrary and depends on the run. To shuffle a set, convert it first with sorted(s) if you need reproducible results, or with list(s) if you don't.
Immutable inputs
Strings and tuples can't be shuffled in place. random.shuffle("abc") raises TypeError. Convert the value to a list, shuffle it, and join it back:
import random
word = "fisher"
letters = list(word)
random.shuffle(letters)
print("".join(letters))Reproducible shuffles
For simulations and tests you often want the same "random" order every time. Use a dedicated random.Random instance with a seed. Don't call random.seed(), because that resets the module-level generator, which every other part of the program also uses.
import random
def shuffled_with_seed(items, seed):
rng = random.Random(seed)
out = list(items)
rng.shuffle(out)
return out
a = shuffled_with_seed(range(10), seed=42)
b = shuffled_with_seed(range(10), seed=42)
print(a == b) # True: same seed, same orderUnpredictable shuffles
The default generator is the Mersenne Twister. It is fast and statistically good, but it is not secure: an attacker who sees enough of its outputs (624 consecutive 32-bit values) can reconstruct its state and predict every later shuffle. When the order must be unpredictable, use the operating system's randomness. Examples are a card game played for money, a lottery draw, or randomized assignment where people have an incentive to cheat.
import secrets
deck = list(range(52))
rng = secrets.SystemRandom()
rng.shuffle(deck)
print(deck)SystemRandom ignores seeds, so its output cannot be reproduced. That is the point of using it. It also has no internal state to exhaust. This removes the problem from the earlier chapter, where Mersenne Twister's 19,937 bits of state cannot reach every ordering of a list with more than about 2,080 elements.
Java, C++, and Go
Java
Collections.shuffle takes a List. The trap is Arrays.asList on a primitive array. It produces a List<int[]> with a single element, so the shuffle silently does nothing useful. Use a boxed array such as Integer[], because Arrays.asList wraps it as a list view that writes through to the array.
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class ShuffleDemo {
public static void main(String[] args) {
Integer[] boxed = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
List<Integer> view = Arrays.asList(boxed);
Collections.shuffle(view, new Random(42));
System.out.println(Arrays.toString(boxed)); // the array itself is shuffled
int[] primitive = {0, 1, 2, 3};
System.out.println(Arrays.asList(primitive).size()); // 1, not 4
}
}For secure shuffles, pass a java.security.SecureRandom. In multithreaded code, pass ThreadLocalRandom.current() instead of sharing one Random. A shared Random is safe to use from several threads, but they contend on its internal state.
C++
std::shuffle requires you to pass a generator explicitly. This is the reason it replaced std::random_shuffle, which often used rand() internally and inherited its small range and weak quality.
#include <algorithm>
#include <iostream>
#include <numeric>
#include <random>
#include <vector>
int main() {
std::vector<int> v(10);
std::iota(v.begin(), v.end(), 0);
std::random_device rd;
std::mt19937_64 gen(rd());
std::shuffle(v.begin(), v.end(), gen);
for (int x : v) std::cout << x << ' ';
std::cout << '\n';
}Seeding mt19937_64 from one random_device call gives it only 32 bits of entropy, even though its state is far larger. That is enough for games and tests. It is not enough when you need every permutation of a large array to be reachable.
Go
rand.Shuffle doesn't need to know your element type. You give it the length and a swap function:
package main
import (
"fmt"
"math/rand"
)
func main() {
words := []string{"ace", "king", "queen", "jack", "ten"}
rand.Shuffle(len(words), func(i, j int) {
words[i], words[j] = words[j], words[i]
})
fmt.Println(words)
}Since Go 1.20 the global generator is seeded randomly at startup. For reproducible runs, create your own source with rand.New(rand.NewSource(seed)). For secure shuffles, math/rand is the wrong package. Build Fisher-Yates on crypto/rand instead.
JavaScript: The Sort-Comparator Trap
JavaScript has no built-in shuffle. A popular one-liner fills the gap badly:
function badShuffle(arr) {
return arr.sort(() => Math.random() - 0.5);
}
const counts = {};
for (let t = 0; t < 60000; t++) {
const key = badShuffle([1, 2, 3]).join("");
counts[key] = (counts[key] || 0) + 1;
}
console.log(counts);Run this and the six counts will be far from 10,000 each. A sorting algorithm assumes the comparator is consistent: if a < b now, then a < b later. A random comparator breaks that assumption. The algorithm does a variable number of comparisons, each with two outcomes, and the resulting probabilities don't divide evenly across 3! orderings. The exact skew depends on which sort algorithm the engine uses, so the bias is different in different browsers. It is also O(n log n), which is slower than Fisher-Yates.
Use the shuffle function with rejection sampling from the earlier chapter on unbiased indices, or a library function that is documented to use Fisher-Yates.
Choosing a Generator
| Need | Python | Java | C++ | Go |
|---|---|---|---|---|
| Fast, not reproducible | `random.shuffle` | `ThreadLocalRandom.current()` | `mt19937_64` seeded from `random_device` | global `rand.Shuffle` |
| Reproducible | `random.Random(seed)` | `new Random(seed)` | `mt19937_64(seed)` | `rand.New(rand.NewSource(seed))` |
| Unpredictable | `secrets.SystemRandom()` | `SecureRandom` | Fisher-Yates over `random_device` (check your platform) | Fisher-Yates over `crypto/rand` |
Exercise
A Python function contains cards = random.shuffle(cards) and later crashes with "TypeError: 'NoneType' object is not iterable". What is wrong, and what are the two correct fixes?
Show answer
random.shuffle shuffles the list in place and returns None, so the assignment replaces the list with None. One fix is to call random.shuffle(cards) without assigning its result. The other is to write cards = random.sample(cards, k=len(cards)) if you want a new shuffled list and need the original left unchanged.
Exercise
A Java developer writes int[] ids = {...}; Collections.shuffle(Arrays.asList(ids)); and the array never changes order. Why, and how do you fix it?
Show answer
Arrays.asList on an int[] produces a List<int[]> containing one element, the array itself. Shuffling a one-element list changes nothing. Fix it by using an Integer[], whose Arrays.asList view writes through to the array, or by running Fisher-Yates directly on the int[].
Exercise
An online poker site shuffles with random.Random(int(time.time())).shuffle(deck). Name two separate weaknesses and the fix.
Show answer
First, the seed is the current second, so an attacker can try every plausible timestamp and recreate the deck. Second, Mersenne Twister is predictable even with a good seed, because its state can be recovered from observed outputs, and its seeded state can only reach a tiny fraction of the 52! orderings. The fix is secrets.SystemRandom().shuffle(deck).