How to Shuffle a Deck of Cards in Python?

Estimated read time 2 min read

To shuffle a deck of cards in Python, you can use the random module, which provides a way to generate random numbers and shuffle lists. Here’s an example of how to shuffle a deck of cards in Python:

import random

# Define the ranks, suits, and cards
ranks = ['Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King']
suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades']
cards = [(rank, suit) for rank in ranks for suit in suits]

# Shuffle the cards
random.shuffle(cards)

# Print the shuffled deck of cards
for card in cards:
    print(card[0] + ' of ' + card[1])

In this example, the ranks and suits of the cards are defined using lists, and the cards list is created using a list comprehension that combines all possible combinations of ranks and suits. The random.shuffle() function is then used to shuffle the cards list in a random order. Finally, the shuffled deck of cards is displayed on the console by looping over the shuffled cards list and printing each card in the format rank of suit.

When you run this code, you will see a shuffled deck of cards printed on the console in a random order. Note that this technique can be used to shuffle any list of items in Python, not just a deck of cards.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply