How to shuffle a deck of cards in Python

Shuffling a deck of cards is essential in various card games to ensure fairness and unpredictability. In Python, we have libraries like itertools and random that provide functionalities to efficiently manipulate and shuffle lists. Understanding how to shuffle a deck of cards programmatically is crucial for implementing card games and serves as a practical exercise in list manipulation and randomization techniques in Python.

Suppose we are tasked with developing a Python program to simulate shuffling a standard deck of playing cards and drawing three cards from the shuffled deck. In this answer, we will demonstrate the process of creating a deck of cards, shuffling them, and then drawing a specified number of cards from the shuffled deck.

Creating a deck of cards

We will create a deck of cards by:

import itertools
# Create a deck of cards
ranks = list(range(1, 14))
suits = ['Spade', 'Heart', 'Diamond', 'Club']
deck = list(itertools.product(ranks, suits))
  • We use itertools.product() to generate all possible combinations of ranks and suits, creating a standard deck of 52 cards.

Shuffling the deck

Then, we will shuffle the deck using the shuffle method of random library:

import random
# Shuffle the deck
random.shuffle(deck)

The random.shuffle() function shuffles the elements of the deck list in place, ensuring a randomized order.

Drawing cards

Now, let’s draw the three random cards:

# Draw five cards
print("We got:")
for i in range(3):
print(f"{deck[i][0]} of {deck[i][1]}")

We loop through the first three elements of the shuffled deck and print each card’s rank and suit.

Complete program

Now let’s test the whole program to shuffle the deck of cards:

import random
import itertools
# Create a deck of cards
ranks = list(range(1, 14))
suits = ['Spade', 'Heart', 'Diamond', 'Club']
deck = list(itertools.product(ranks, suits))
# Shuffle the deck
random.shuffle(deck)
# Draw five cards
print("We got:")
for i in range(3):
print(f"{deck[i][0]} of {deck[i][1]}")

Conclusion

Shuffling a deck of cards programmatically in Python involves creating a standard deck, shuffling its elements randomly, and then drawing cards from the shuffled deck. Through this exercise, we have explored the usage of Python libraries, such as itertools and random, to accomplish these tasks efficiently. Understanding these techniques facilitates the implementation of card games and enhances your proficiency in list manipulation and randomization in Python.

Copyright ©2024 Educative, Inc. All rights reserved