Python Program to Shuffle Deck of Cards



When it is required to shuffle a deck of cards using Python, the 'itertools' and the 'random' packages need to be used. Random library has a method named 'shuffle' that can be used to mix up and show the data.

Below is a demonstration for the same −

Example

Live Demo

import itertools, random my_deck = list(itertools.product(range(1,11),['Spade','Heart','Diamond','Club'])) print("The cards are being shuffled") random.shuffle(my_deck) print("Cards are drawn at random") print("They are : ") for i in range(5):    print(my_deck[i][0], "of", my_deck[i][1])

Output

The cards are being shuffled Cards are drawn at random They are : 1 of Diamond 5 of Diamond 4 of Club 2 of Spade 4 of Heart

Explanation

  • The required packages are imported.
  • The 'itertools' package is used, and the 'product' method is used to get the deck of cards in a list format.
  • This list is shuffled using the 'shuffle' method present in the 'random' library.
  • Then, relevant message is displayed.
  • The above shuffled data is iterated over.
  • This is displayed on the console.
Updated on: 2021-03-13T05:50:44+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements