Python Shuffle List | Shuffle a Deck of Card

The concept of shuffle in Python comes from shuffling deck of cards. Shuffling is a procedure used to randomize a deck of playing cards to provide an element of chance in card games. Shuffling is often followed by a cut, to help ensure that the shuffler has not manipulated the outcome. In Python, the shuffle list is used to get a completely randomized python list.

The shuffle() function can be used to shuffle a list. The shuffle is performed in place, meaning that the list provided as an argument to the shuffle() function is shuffled rather than a shuffled copy of the list being made and returned.
We can shuffle a list like a deck of cards with the shuffle() function/ method. This shuffles the list in-place. In other words, it does not need to create a new list to put shuffled items into one by one.

Python Shuffle a List Using shuffle() Function

The shuffle() function in Python random module can be used to shuffle a list.

Shuffling is performed in place, meaning that the list provided as an argument to the shuffle() function is shuffled rather than a shuffled copy of the list being made and returned.

The shuffle() method takes a sequence (list, string, or tuple) and reorganizes the order of the items.

Syntax of shuffle() Function to Python Shuffle List

random.shuffle(lstfunction)

Parameters

  • lst − Required. A sequence. Can be a list, a tuple, or a string.
  • random − Optional. The name of a function that returns a number between 0.0 and 1.0. If not specified, the function random() will be used.

Return Value of shuffle() Function

This method returns the reshuffled list.

Flowchart of shuffle() Function to Python Shuffle List

Python Shuffle List Flowchart of shuffle()

Let’s Move into the Examples.

Example 1: Basic Python Program to Python Shuffle List Using shuffle() Function

import random

countries=["India", "China", "USA", "UK", "France"]
random.shuffle(countries)

print(countries)

Output:

['USA', 'France', 'China', 'UK', 'India']
python shuffle() example

Explanation:

In the above example, we have shuffled the Python list of countries. First, we have imported the random module. As the shuffle method or function is present in the random Module. So we have to first import the random Module. After that, we have initialized and created our list of countries. Here you can create any Python list of your choice. Then we shuffled the Python List of countries using the shuffle() function.

Example 2: Shuffling a List n n Number of Times Using for Loop and Range

Using for loop we can shuffle the list for any number of times we want.

import random
mylist =['26','Python','Pool','is','Best','Way','To','Learn','Python']
for x in range(10):
    random.shuffle(mylist)
    print(mylist)

Output:

['26', 'Way', 'is', 'Python', 'To', 'Python', 'Best', 'Pool', 'Learn']
['Pool', '26', 'To', 'Learn', 'Python', 'is', 'Best', 'Python', 'Way']
['26', 'is', 'Pool', 'Way', 'Python', 'To', 'Best', 'Learn', 'Python']
['26', 'Learn', 'Way', 'Pool', 'Best', 'is', 'Python', 'Python', 'To']
['Best', 'Way', 'Python', 'Pool', 'is', 'Learn', 'To', 'Python', '26']
['Python', 'Pool', 'Python', 'Learn', 'Way', 'Best', 'is', 'To', '26']
['Best', '26', 'Learn', 'To', 'is', 'Python', 'Pool', 'Python', 'Way']
['26', 'Python', 'Way', 'is', 'Python', 'To', 'Pool', 'Learn', 'Best']
['is', 'Best', '26', 'Python', 'Python', 'Learn', 'Way', 'Pool', 'To']
['26', 'Python', 'is', 'Pool', 'To', 'Learn', 'Way', 'Python', 'Best']

Explanation:

In this second example, we have taken the Python list [’26’,’Python’,’Pool’,’is’,’Best’,’Way’,’To’,’Learn’,’Python’]. And we want to shuffle this list 10 times. So to get our desired result. We used the Python for loop with range 10 and initialized it. And inside that for loop, we are using the shuffle method of the random module. It will do the shuffling of the list as long as the loop goes on.

Note:

If you want to shuffle the list 20 times. You have to just change the parameter of range(20) function to 20.

Example 3: Shuffling two Python List at once with the same order

Let’s assume if you want to Shuffle two Python lists. But also wants to maintain the same shuffle order. For example, One list contains Country name and the other contains a Capitals.

import random

country = ['India', 'China', 'USA', 'UK']
capital = ['New Delhi', 'Beijing', 'Washington DC', 'London']

print("Lists Before Shuffling")
print("List of Countries Names: ", country)
print("List of Capitals: ", capital)

mapIndexPosition = list(zip(country, capital))
random.shuffle(mapIndexPosition)
country, capital = zip(*mapIndexPosition)

print("\nLists after Shuffling")
print("List of Countries Names: ", country)
print("List of Capitals: ", capital)

Output:

Lists Before Shuffling
List of Countries Names:  ['India', 'China', 'USA', 'UK']
List of Capitals:  ['New Delhi', 'Beijing', 'Washington DC', 'London']

Lists after Shuffling
List of Countries Names:  ('UK', 'China', 'India', 'USA')
List of Capitals:  ('London', 'Beijing', 'New Delhi', 'Washington DC')

Example 1: Basic Python Program to Python shuffle list of lists

Another really interesting use case is when you have nested structures with similar data. In this case, you can simply iterate the lists and apply the shuffle function.
Shuffling list of lists in python with loop. This will shuffle not only the first level of list elements but also the nested ones. This code works only with two levels of sublists but the same approach can be applied for more levels:

import random

mylist = [['a','b','c'],['d','e','f'],['g','h','i']]
random.shuffle(mylist)
for sublist in mylist:
    random.shuffle(sublist)
print(mylist)

Output:

[['d', 'e', 'f'], ['c', 'b', 'a'], ['i', 'h', 'g']]

How to Shuffle a Deck of Card in Python

In this section of the article, you’ll learn to shuffle a deck of cards in Python. Using the shuffle() Function random module.

Python Code to Shuffle Cards

# Python program to shuffle a deck of card

# importing modules
import itertools, random

# make 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(5):
   print(deck[i][0], "of", deck[i][1])

Output:

You got:
10 of Diamond
8 of Heart
11 of Heart
10 of Spade
1 of Club

Explanation:

Note: Run the program again to shuffle the cards.

In the program, we used the product() function in itertools module to create a deck of cards. This function performs the Cartesian product of the two sequences.

The two sequences are numbers from 1 to 13 and the four suits. So, altogether we have 13 * 4 = 52 items in the deck with each card as a tuple. For example,

deck[0] = (1, 'Spade')

Our deck is ordered, so we shuffle it using the function shuffle() in random module.

Finally, we draw the first five cards and display it to the user. We will get different output each time you run this program as shown in our two outputs.

Here we have used the standard modules itertools and random that comes with Python.

Must Read:

How to Convert String to Lowercase in Python
How to Calculate Square Root in Python
Python User Input | Python Input () Function | Keyboard Input
Best Book to Learn Python in 2020
Python Reverse List Using reverse() reversed() and Slicing

Conclusion

So in this article, we have covered the best way to Python Shuffle List. There are many ways to shuffle list in Python but we have chosen the shuffle(). The reason for choosing the Python shuffle() function is quite simple.
1. It’s easy to use.
2. We don’t need to do additional coding.
3. It’s fast and available in the built-in module

So, I hope Now you have completely understood how to shuffle a list in Python.
If you still have any doubts do let us know in the comment section below.

Happy Coding!

Leave a Reply