In this lesson, you will learn how to shuffle a list in Python using the random.shuffle()
function. Also, learn how to shuffle string, dictionary, or any sequence in Python.
When we say shuffle a list, it means a change in the order of list items. For example, shuffle a list of cards.
You’ll learn the following functions of a random module to randomize a list in Python.
Function | Description |
---|---|
random.shuffle(list1) | Shuffle list in-place (preferred way) |
random.sample(seq, len(seq)) | Shuffle list not in place to return a new shuffled list. (non-preferred way) OR To shuffle an immutable sequence such as string or range. |
np.random.shuffle(array) | Shuffling multidimensional array |
Table of contents
- The random.shuffle() function
- Shuffle a List
- Randomly Shuffle Not in Place
- Shuffle Two Lists At Once With Same Order
- Shuffling NumPy Multidimensional Array
- Shuffle a List to Get the Same Result Every time
- Shuffle a String
- Shuffle Range of Integers
- Shuffle a Dictionary in Python
- Shuffle a Python generator
- Next Steps
The random.shuffle()
function
Syntax
random.shuffle(x, random)
It means shuffle a sequence x
using a random
function.
Parameters:
The random.shuffle()
function takes two parameters. Out of the two, random
is an optional parameter.
x
: It is a sequence you want to shuffle such as list.random
: The optional argument random is a function returning a random float number between 0.1 to 1.0. This function decides how to shuffle a sequence. If not specified, by default Python uses therandom.random()
function.
Note: this parameter deprecated since version 3.9, will be removed in version 3.11
Return Value
It shuffles sequence in place and doesn’t return anything, i.e., It returns None. This function changes the position of items in a mutable sequence.
Shuffle a List
Use the below steps to shuffle a list in Python
- Create a list
Create a list using a
list()
constructor. For example,list1 = list([10, 20, 'a', 'b'])
- Import random module
Use a random module to perform the random generations on a list
- Use the shuffle() function of a random module
Use the
random.shuffle(list1)
function to shuffle alist1
in place.
theshuffle()
shuffles the original list, i.e., it changes the order of items in the original list randomly and doesn’t return a new list - Display the shuffled list
As
shuffle()
function doesn’t return anything. Useprint(list1)
to display the original/resultant list. - Get shuffled list instead of modifying the original list
Use the random.sample() function to shuffle the list not in place to get the new shuffled list in return instead of changing the original list. OR
Make a copy of the original list before shuffling (Ideal way) - Customize the shuffling if needed
If you want to perform shuffling as per your need, you can pass a custom function in the place of the
random
argument, which will dictate theshuffle()
function on how to randomize a list’s items.
Example: –
import random
number_list = [7, 14, 21, 28, 35, 42, 49, 56, 63, 70]
# Original list
print(number_list)
# Output [7, 14, 21, 28, 35, 42, 49, 56, 63, 70]
# List after first shuffle
random.shuffle(number_list)
print(number_list)
# Output [42, 28, 14, 21, 7, 35, 49, 63, 56, 70]
# List after second shuffle
random.shuffle(number_list)
print(number_list)
# Output [14, 21, 70, 28, 49, 35, 56, 7, 42, 63]
Note: As you can see in the output, the positions of list items are changed.
Randomly Shuffle Not in Place
As you know, the shuffle()
works in place and returns None, i.e., it changes the order of items in the original list randomly. But most of the time, we need the original list or sequence.
We can keep the original list intact using the following two ways. These options don’t modify the original list but return a new shuffled list.
Option 1: Make a Copy of the Original List
Make a copy of the original list before shuffling (Ideal and preferred)
import random
numbers = [33, 66, 99, 188, 256, 412, 748]
# copy to new list
new_list = numbers.copy()
# shuffle the new list
random.shuffle(new_list)
print("Original list : ", numbers)
# [33, 66, 99, 188, 256, 412, 748]
print("List after shuffle", new_list)
# Output [188, 412, 33, 256, 66, 748, 99]
Option 2: Shuffle list not in Place using random.sample()
Use the random.sample()
function to shuffle list not in place to get the new shuffled list in return instead of changing the original list
The random.sample() function returns the random list with the sample size you passed to it. For example, sample(myList, 3)
will return a list of 3 random items from a list.
If we pass the sample size the same as the original list’s size, it will return us the new shuffled list.
Let’s see the example. In this example, I am shuffling the list of Employee objects.
import random
# custom class
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
emp1 = Employee("Kelly", 10000)
emp2 = Employee("Abigail", 8000)
emp3 = Employee("Sampson", 12000)
emp4 = Employee("Joe", 7000)
# list with 4 objects
emp_list = [emp1, emp2, emp3, emp4]
# print original list
for emp in emp_list:
print(emp.name, emp.salary, end=', ')
# Output Kelly 10000, Abigail 8000, Sampson 12000, Joe 7000,
# shuffle list of objects
# sample size (k) = length of a list
shuffledList = random.sample(emp_list, k=len(emp_list))
print("\nPrinting new shuffled list of employee object")
for emp in shuffledList:
print(emp.name, emp.salary, end=', ')
# Output Joe 7000, Kelly 10000, Abigail 8000, Sampson 12000,
Waring: As per the official Python documentation, for small len(x)
, the total number of permutations of x
can quickly grow more extensive than the period of most random number generators. This implies that most permutations of a long sequence can never be generated. For example, a sequence of length 2080 is the largest that can fit within the Mersenne Twister random number generator period. So I advise you to use the use first approach.
Shuffle Two Lists At Once With Same Order
Let’s assume if you want to Shuffle two lists and maintain the same shuffle order. For example, One list contains employee names, and the other includes a salary. Let’s see how to randomize multiple lists by maintaining their order.
import random
# list of names
employees = ['Jon', 'Emma', 'Kelly', 'Jason']
# list of numbers
salary = [7000, 6500, 9000, 10000]
# Lists before Shuffling
print("Employee Names: ", employees)
# output ['Jon', 'Emma', 'Kelly', 'Jason']
print("Employee Salaries: ", salary)
# Output [7000, 6500, 9000, 10000]
# To Shuffle two List at once with the same order
mapIndexPosition = list(zip(employees, salary))
random.shuffle(mapIndexPosition)
# make list separate
list1_names, list2_salary = zip(*mapIndexPosition)
# Lists after Shuffling
print("Employee Names: ", list1_names)
# Output ('Emma', 'Jon', 'Kelly', 'Jason')
print("Employee Salary: ", list2_salary)
# output (6500, 7000, 9000, 10000)
# Employee name and salary present index 3
print(list1_names[3], list2_salary[3])
# Output Jason 10000
Shuffling NumPy Multidimensional Array
NumPy module has a numpy.random
package to generate random data. In this example, I am using Python’s Numpy module to create a 2d array. Also, Using numpy.random.shuffle()
function, we can shuffle the multidimensional array.
import numpy as np
print('Before shuffling 2dimensional array')
sample_array = np.arange(100, 240, 10)
sample_array = sample_array.reshape(7, 2)
print(sample_array)
print('After shuffling 2dimensional array')
np.random.shuffle(sample_array)
print(sample_array)
Output:
Before shuffling 2dimensional array [[100 110] [120 130] [140 150] [160 170] [180 190] [200 210] [220 230]] After shuffling 2dimensional array [[160 170] [140 150] [200 210] [220 230] [120 130] [100 110] [180 190]]
Shuffle a List to Get the Same Result Every time
Let’s how to seed the random generator in such a way that shuffling produces the same result every time. Using the seed()
and shuffle()
together, we can generate the same shuffled list every time.
Do you know how PRNG works in Python?
Python’s random module is not truly random. It is pseudo-random (PRNG), i.e., deterministic. The random module uses the seed value as a base to generate a random number. By default, current system time is used as a seed value. If we change the seed value, we can change the output.
import random
numbers = [10, 20, 30, 40, 50, 60]
print("Original list: ", numbers)
# shuffle 3 times
for i in range(3):
# seed PRNG
random.seed(4)
# shuffle list
random.shuffle(numbers)
print("result list ", numbers)
Output:
Original list: [10, 20, 30, 40, 50, 60] result list [40, 60, 50, 10, 30, 20] result list [10, 20, 30, 40, 50, 60] result list [40, 60, 50, 10, 30, 20]
Note: We are getting the same list because we use the same seed value before calling the shuffle function. This is just a simple example. To make it work with any list, we need to find the exact seed root number for that list, which will produce the output we desire.
Shuffle a String
In this section, we will see how to shuffle String in Python. But it is not as simple as shuffling a list. You will get an error if you try to shuffle a string using the shuffle()
method.
Because a string is an immutable type, and You can’t modify the immutable objects in Python. The random.shuffle()
doesn’t’ work with String. I.e., It can’t accept string argument. Let’s understand this with the help of the following example.
import random
string_one = "PYnative"
random.shuffle(string_one)
print(string_one)
# TypeError: 'str' object does not support item assignment.
We have a solution to this. We can shuffle a string using various approaches. Let see each one by one.
Shuffle a String by Converting it to a List
Convert String to list and Shuffle the list randomly, again convert the shuffled list into String
import random
sample_str = "PYnative"
# Original string
print(sample_str)
# 'PYnative'
# convert string into list
char_list = list(sample_str)
# shuffle list
random.shuffle(char_list)
# convert list to string
final_str = ''.join(char_list)
# shuffled list
print(final_str)
# Output 'tiaeYPvn'
Approach Two: Shuffling a String, not in place
Using this approach, we can keep the original string unchanged and get the new shuffled string in return. Also, we don’t need to convert the string to a list to get the shuffled string.
The sample() function returns a sample from a sequence as per the sample size you passed to it. For example, sample(str, 3)
will return a list of 3 random characters from a list.
If we pass the sample size the same as the string size, it will return us the new shuffled string of characters.
import random
sample_str = "PYnative"
print(sample_str)
# 'PYnative'
# shuffle string using random.sample()
final_str = ''.join(random.sample(sample_str, len(sample_str)))
print(final_str)
# Output 'ePtaYivn'
Shuffle Range of Integers
A range() function returns a sequence of numbers.
The range()
doesn’t return the list, so when you try to run shuffle(range(10))
, you will get an error. To shuffle numbers in the range(10)
, first convert the range to a list
.
import random
# Shuffle a range of numbers
numbers = list(range(10))
random.shuffle(numbers)
print(numbers)
# Output [1, 7, 0, 3, 2, 9, 6, 8, 4, 5]
Shuffle a Dictionary in Python
Shuffling a dictionary is not possible in Python. However, we can rearrange the order of keys of a dictionary.
- Fetch all keys from a dictionary as a list.
- Shuffle that list and access dictionary values using shuffled keys.
import random
student_dict = {'Eric': 80, 'Scott': 75, 'Jessa': 95, 'Mike': 66}
print("Dictionary Before Shuffling")
print(student_dict)
keys = list(student_dict.keys())
random.shuffle(keys)
ShuffledStudentDict = dict()
for key in keys:
ShuffledStudentDict.update({key: student_dict[key]})
print("\nDictionary after Shuffling")
print(ShuffledStudentDict)
Output:
Dictionary before shuffling {'Eric': 80, 'Scott': 75, 'Jessa': 95, 'Mike': 66} Dictionary after shuffling {'Jessa': 95, 'Eric': 80, 'Mike': 66, 'Scott': 75}
Shuffle a Python generator
The random.shuffle()
needs to know the sequence’s size to shuffle the sequence uniformly. If you try to shuffle a generator object using it, you will get a TypeError: the object of type 'generator' has no len()
.
As the generator cannot provide us the size we need to convert it into a list to shuffle it.
import random
def sample_generator():
yield 25
yield 50
yield 75
yield 100
print("Generator")
for i in sample_generator():
print(i, end=", ")
# Shuffle generator
newList = list(sample_generator())
random.shuffle(newList)
print("\nPrint shuffled generator")
for i in newList:
print(i, end=", ")
Next Steps
I want to hear from you. What do you think of this article on random.shuffle()
? Or maybe I missed one of the usages of random.shuffle()
. Either way, let me know by leaving a comment below.
Also, try to solve the following exercise and quiz to have a better understanding of working with random data in Python.