random.shuffle
The classic trap: shuffle() changes the list you pass and returns None, so x = random.shuffle(x) loses the list. Strings and tuples cannot be shuffled in place at all.
Demo
import random random.seed(42) items = ['a', 'b', 'c', 'd'] result = random.shuffle(items) (result, items)
shuffle() walks the list from the end: for each position i it draws j with _randbelow(i + 1) and swaps items i and j, so n items cost n - 1 calls to _randbelow. Same seed and same items, same order. Note that sample(items, k=len(items)) draws differently, so with seed 42 the copy is a, d, b, c while the in-place shuffle gives c, b, d, a.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| x | list (mutable sequence) | yes | Reordered in place. Needs len() and item assignment: a str or tuple raises TypeError. |
Return value
None — Always None: the list itself is reordered.
Common patterns
import random deck = [r + s for s in 'SHDC' for r in 'A23456789TJQK'] random.shuffle(deck) hand, deck = deck[:5], deck[5:]
import random shuffled = random.sample(items, k=len(items))
import random letters = list(word) random.shuffle(letters) scrambled = ''.join(letters)
import random combined = drug + placebo for _ in range(10_000): random.shuffle(combined) new_diff = mean(combined[:len(drug)]) - mean(combined[len(drug):])
Examples
Pitfalls
import random random.seed(42) x = [1, 2, 3, 4, 5] x = random.shuffle(x) print(x)
import random random.seed(42) x = [1, 2, 3, 4, 5] random.shuffle(x) x
import random random.seed(42) t = ('a', 'b', 'c') random.shuffle(list(t)) t
import random random.seed(42) t = ('a', 'b', 'c') random.sample(t, k=len(t))
When to use
- Randomizing the order of a list you own: decks, playlists, quiz questions
- Permutation tests and randomized algorithms
- Keeping the original order → sample(x, k=len(x))
- Strings and tuples → sample() or a list copy
- Very long lists when every permutation must be possible: the Mersenne Twister period only covers all orderings up to 2080 items
Notes
FAQ
It works in place, like list.sort(): the list you passed is reordered and None is returned so that nobody mistakes it for a copy. Use the list itself afterwards, or random.sample(x, k=len(x)) for a new list.