Seeded Shuffle Deals The Same Hands
random.Random(seed) makes shuffle reproducible: the same deck reshuffled with the same seed replays card-for-card, which is what deal logs and tests need.
Code
import random
# Seeded Random instance: the same deck shuffles to the same order every run
rng = random.Random(2026)
suits = ["♠", "♥", "♦", "♣"]
ranks = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"]
deck = [r + s for s in suits for r in ranks]
print("top before:", deck[0]) # 2♠ - the unshuffled order is predictable
rng.shuffle(deck) # Fisher-Yates, shuffles in place
print("top after:", deck[0])
print("size kept:", len(deck) == 52)
# Deal by slicing: four hands take every 4th card, 13 cards each
hands = [deck[i::4] for i in range(4)]
print("hand sizes:", [len(h) for h in hands])
# A fresh deck with the same seed replays the exact same shuffle
fresh = [r + s for s in suits for r in ranks]
random.Random(2026).shuffle(fresh)
print("replay equals:", fresh == deck)Output
Captured from a sandboxed run of this snippet in the build pipeline.
top before: 2♠
top after: 5♦
size kept: True
hand sizes: [13, 13, 13, 13]
replay equals: TrueWhat the demo replays
A Random(2026) instance shuffles a 52-card deck built from suits and ranks. The top card before any shuffle is the predictable 2 of spades; after rng.shuffle(deck) the printed top reflects the seeded Fisher-Yates order and the size check still reports 52.
Dealing slices every 4th card into four hands, printing 13 cards each. The replay builds an identical fresh deck and shuffles it with a new Random(2026); fresh == deck prints True, proving the same seed reproduces the exact same shuffle.
Practical notes
- Module-level random.shuffle uses global state; a seeded instance does not.
- Slicing deck[i::4] deals round-robin without a loop.
Interactive Tools for This Topic
FAQ
- Why seed the shuffle at all?
- Deal logs, regression tests and replays need identical sequences; the final True line of the demo shows seed 2026 reproducing the order card-for-card.
Report a problem with this exampleOpens a pre-filled issue on GitHub.