Shuffle Deck of Cards in Python

(Last Updated On: 26/09/2023)

Welcome to our tutorial on how to shuffle a deck of cards in Python! In this tutorial, we will be discussing how to use the built-in modules “itertools” and “random” to create and shuffle a deck of cards.

Python Program to Shuffle a Deck of Cards

The first step in shuffling a deck of cards is to create the deck itself. In this example, we are using the “itertools” module to create a deck of cards. The “itertools” module provides a function called “product()” which takes two arguments and returns a cartesian product of the input arguments. So, to create a deck of cards, we pass the range of card numbers and the types of cards as arguments to the “product()” function.

This line of code creates a deck of cards with numbers from 1 to 13 and four types of cards (Spade, Heart, Diamond, Club). The list() function is used to convert the returned object to a list, so that we can shuffle it.

Once we have the deck of cards, we can use the “random” module to shuffle the deck of cards. The “random” module provides a function called “shuffle()” which takes a list as an argument and shuffles the elements of that list. This line of code shuffles the deck of cards.

# Python program to shuffle a deck of card

# importing modules
import itertools, random

# make a deck of cards
# we used the product() function in itertools module to create a deck of cards
deck = list(itertools.product(range(1,14),['Spade','Heart','Diamond','Club']))

# shuffle the cards
random.shuffle(deck)

# draw five cards
print("You got:")
for i in range(3):
   print(deck[i][0], "of", deck[i][1])

Output:

Finally, we can use the “for” loop and the “print()” function to draw cards from the deck. We can specify the number of cards we want to draw and print them out.

You got:
4 of Spade
12 of Club
2 of Diamond

In this example, we are using the “for” loop to iterate over a range of 3, which means we are drawing 3 cards from the deck. The “deck[i][0]” and “deck[i][1]” are used to access the elements of the deck list. The first element of the list represents the card number, and the second element represents the card type.

In conclusion, shuffling a deck of cards in Python is a simple task that can be achieved using the built-in modules “itertools” and “random”. By understanding how to use these modules, you’ll be able to create and shuffle a deck of cards in a more precise way.

Additionally, this example illustrates the use of built-in modules, lists, for loop, and print functions in Python. With this tutorial, you now have a solid understanding of how to shuffle a deck of cards in Python. You can use this concept to create a wide range of card games, simulations, and other fun projects.

For More Python Programming Exercises and Solutions check out our Python Exercises and Solutions

About The Author