Sub topic 12
Using Your Language's Built-In Shuffle
This chapter assumes you already know how Fisher-Yates works, why modulo bias happens, and how the size of a generator's state limits which permutations it can reach. In real projects you rarely write the loop yourself. You call a library function. The work that remains is to pick the right function and the right randomness source.
Python's standard tools
Python's random.shuffle is an in-place Durstenfeld shuffle. It draws each index with an internal rejection-sampling routine, so it has no modulo bias. random.sample returns a new shuffled list and leaves the input unchanged.
import random
deck = list(range(52))
random.shuffle(deck) # in place
shuffled_copy = random.sample(deck, k=len(deck)) # new list, original unchanged
secure = random.SystemRandom()
secure.shuffle(deck) # uses the operating system's randomness source
print(deck[:5], shuffled_copy[:5])The default generator is the Mersenne Twister, which has 19,937 bits of state. The Python documentation notes that 2080 is the largest sequence length whose permutations can all fit within that generator's period. A 52-card deck is well inside that limit. The Mersenne Twister is still predictable, though. An observer who sees about 624 of its outputs can reconstruct its state and predict every later shuffle. For card games with money at stake, lotteries, or anything security-related, use random.SystemRandom or the secrets module.
Other languages
| Language | Recommended call | Notes |
|---|---|---|
| Python | `random.shuffle(xs)` | Pass through `SystemRandom` when results must be unpredictable |
| NumPy | `np.random.default_rng().shuffle(a)` | Shuffles along the first axis; `permutation` returns a copy |
| Java | `Collections.shuffle(list, rnd)` | The default `java.util.Random` has 48 bits of state, so it cannot reach every ordering of more than 16 items (17! > 2^48). Pass a `SecureRandom` instead |
| C++ | `std::shuffle(b, e, gen)` | `std::random_shuffle` was deprecated in C++14 and removed in C++17 |
| Go | `rand.Shuffle(n, swap)` | You supply the swap function |
| C# | `Random.Shared.Shuffle(span)` | Available from .NET 8 |
| Rust | `xs.shuffle(&mut rng)` | Requires the `rand` crate's `SliceRandom` trait |
| JavaScript | none built in | Write Fisher-Yates using rejection sampling over `crypto.getRandomValues` |
Choosing a call
Common mistakes
- Seeding the generator from the clock on every call. Calls made in the same second get the same seed and produce the same "random" order.
- Shuffling a copy and then using the original. In Python,
random.shufflereturnsNone, sodeck = random.shuffle(deck)throws your list away. - Calling
random.shuffleon an immutable sequence such as a tuple or string. It raisesTypeError. Userandom.sample(s, k=len(s))instead. - Calling
random.seed(42)in production code that needs variety. Fixed seeds belong in tests, where you want results you can reproduce.
Exercise
A Java poker server deals by calling Collections.shuffle(deck) on a 52-card list, with no second argument. Explain what is wrong and give the fix.
Show answer
Without a second argument, Collections.shuffle uses a java.util.Random with 48 bits of state. That generator can produce at most 2^48 different orderings, which is far fewer than 52! (about 2^225), so most deals can never occur. Its outputs can also be predicted after only a few observations. The fix is Collections.shuffle(deck, new SecureRandom()).
Exercise
Why does cards = random.shuffle(cards) leave cards set to None, and what are two correct ways to write this line?
Show answer
random.shuffle changes the list in place and returns None, so the assignment replaces the list with None. Either call random.shuffle(cards) without assigning the result, or write cards = random.sample(cards, k=len(cards)) to get a new shuffled list.