AppDividend
Latest Code Tutorials

Python Random shuffle() Method Example

0

Python random shuffle() function shuffles string or any sequence. To shuffle a list means we are rearranging the order of the elements in the list randomly. If you need to perform shuffling as per your requirement, then you can pass the custom random method in the place of a random argument, which will dictate shuffle() function on how to randomizes the item of the list.

Python random shuffle()

The shuffle() method in Python takes a sequence (list, string, or tuple) and reorganizes the order of the items. Python’s random is not actual random module; it is a pseudo-random(it is PRNG). For example, deterministic.

The random module uses a seed value as the base to generate a random number. Bydefault, the current system time is used as a seed value. If we modify the seed value, we can change the output.

See the following syntax of random.shuffle() method.

Syntax

random.shuffle(sequence, random)

Parameters

The shuffle() method takes two parameters. Out of the two, random is the optional parameter.

The sequence is any sequence you want to shuffle. The sequence can be the list, string, or tuple.

The optional argument random is the function returning a random float number between 0.1 to 1.0. If not specified, then by default, Python uses random.random() function.

Return Value

The random.shuffle() shuffles in place and doesn’t return anything. For example, the shuffle() returns None. The shuffle() function changes the position of items in a mutable sequence.

Example of random shuffle

import random

number_list = [19, 11, 21, 28, 35, 42, 49, 56, 63, 70]
print("Original list:", number_list)

random.shuffle(number_list)
print("List after first shuffle:", number_list)

random.shuffle(number_list)
print("List after second shuffle:", number_list)

Output

Original list: [19, 11, 21, 28, 35, 42, 49, 56, 63, 70]
List after first shuffle: [56, 11, 49, 70, 28, 35, 42, 21, 63, 19]
List after second shuffle: [56, 49, 28, 11, 42, 63, 70, 35, 21, 19]

The random.shuffle() works in place and returns None; For example, it changes the order of elements in the list randomly.

But most of the time, we need the initial list. Now, how to get an initial or original list?

We can get an original list using the following two ways. These options don’t change the original list, but it returns the new shuffled list.

  1. Make a copy of an original list into a new list before shuffling (Ideal and preferred).
  2. Shuffle list not in place to get the shuffled list in return instead of changing an original list.

See the following code.

import random

numbers = [29, 18, 19, 21, 46, 47]

# copy to new list
new_list = numbers[:]

# shuffle the new list
random.shuffle(new_list)

print("Original list : ", numbers)
print("List after shuffle", new_list)

Output

Original list :  [29, 18, 19, 21, 46, 47]
List after shuffle [47, 18, 46, 19, 29, 21]

In this example, first, we have imported a random module and then defined a numbers list.

Then we copied that list to a new list called new_list.

And then, we shuffled the new_list and printed numbers list and new_list.

Shuffling a String

If we try to rearrange the string’s characters using random shuffle(), you will get the error because the string is immutable and you can’t change the immutable objects in Python.

The random.shuffle() method adjusts the position of the elements. It modifies the original object. The random.shuffle() doesn’t’ work with String. I.e., It can’t accept string argument.

import random

string_el = "Millie"
random.shuffle(string_el)
print(string_el)

Output

Traceback (most recent call last):
  File "app.py", line 4, in <module>
    random.shuffle(string_el)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/random.py", line 307, in shuffle
    x[i], x[j] = x[j], x[i]
TypeError: 'str' object does not support item assignment

In the output, we got an error saying: TypeError: ‘str’ object does not support item assignment.

To shuffle a string, we have to follow the below steps.

  1. Convert Python String to List
  2. Shuffle the list randomly.
  3. Convert back to shuffled List to String.

See the following code.

import random

string_el = "Millie"
print('The orignal string is: ', string_el)
# Convert String to List
char_list = list(string_el)

# shuffle list
random.shuffle(char_list)

# Convert list to string
shuffled_str = ''.join(char_list)
print('The shuffled string is: ', shuffled_str)

Output

The orignal string is:  Millie
The shuffled string is:  lliMie

Shuffling tuple in Python

If you want to direct shuffle tuple, then you will get an error.

import random

tup = (11, 21, 19, 46, 18)
random.shuffle(tup)

We get the error like TypeError: ‘tuple’ object does not support item assignment.

To shuffle tuple elements, we can follow the below steps.

  1. Convert Python tuple to List
  2. Shuffle the list randomly.
  3. Convert back to shuffled List to Tuple.

See the following code.

import random

tup = (11, 21, 19, 46, 18)
lst = list(tup)
random.shuffle(lst)
tu = tuple(lst)
print(tu)

Output

(21, 11, 46, 19, 18)

Shuffling a dictionary in Python

Shuffling a dictionary in Python is not possible. However, we can rearrange the iteration order of keys of the dictionary.

Fetch all keys from the dictionary and add it in the list, shuffle that list, and access the dictionary values using newly shuffled keys.

See the following code.

import random

netflixDict = {'The Witcher': 'Geralt', 'S Things': 'Eleven',
               'S Ed': 'Otis', 'Rick and M': 'Morty'}
print("Dictionary Before Shuffling")
print(netflixDict)
keys = list(netflixDict.keys())
random.shuffle(keys)

ShufflednetflixDict = dict()
for key in keys:
    ShufflednetflixDict.update({key: netflixDict[key]})

print("\nDictionary after Shuffling")
print(ShufflednetflixDict)

Output

Dictionary Before Shuffling
{'The Witcher': 'Geralt', 'S Things': 'Eleven', 'S Ed': 'Otis', 'Rick and M': 'Morty'}

Dictionary after Shuffling
{'S Things': 'Eleven', 'The Witcher': 'Geralt', 'S Ed': 'Otis', 'Rick and M': 'Morty'}

In this example, we have defined a dictionary then use the dict.keys() method to get the list of keys of the dictionary and then shuffle the keys using a random shuffle() method.

Then we map the keys with dictionary values using for loop and dict.update() method.

In the final output, we get the shuffled dictionary.

Shuffling multidimensional array

To shuffle a multidimensional array in Python, you can use a numpy random module.

Python’s NumPy module has a numpy.random module to generate the random data. In this example, I am using Python numpy to create a 2D array.

Also, Using the numpy.random.shuffle() method, we can shuffle the multidimensional array. Okay, now let’s see how to shuffle a multidimensional array in Python.

import numpy

print("Before Shufflling 2D array")
dataArray = numpy.arange(100, 240, 10)
dataArray = dataArray.reshape(7,2)
print (dataArray)

print("After Shufflling 2D array")
newArray = numpy.random.shuffle(dataArray)
print (dataArray)

Output

Before Shufflling 2D array
[[100 110]
 [120 130]
 [140 150]
 [160 170]
 [180 190]
 [200 210]
 [220 230]]
After Shufflling 2D array
[[120 130]
 [180 190]
 [220 230]
 [140 150]
 [100 110]
 [160 170]
 [200 210]]

In this example, we have used the np arange() method to generate random array and then reshape it to a 2D array. Then use the numpy random shuffle() method to shuffle the 2D array.

Conclusion

In this tutorial, we have seen how to use a random shuffle() method to shuffle the list, tuple, dictionary, array, and multidimensional array.

That is it for this tutorial.

See Also

Python random sample()

Python random choice()

Numpy random rand()

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.