random.shuffle

Full name
random.shuffle
Library
random
Syntax

random.shuffle(x)

Description

The random.shuffle function shuffles the sequence x in-place.

If you want to shuffle an immutable sequence x, you can use:

x = sample(x, k = len(x))
Parameters
  • x: Sequence to shuffle. It must be mutable because, in any other case, the function will return an error.
Result

The random.shuffle function returns the sequence x passed as an argument shuffled.

Examples

If we have a list made up of the names of the days of the week:

days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]

...we could shuffle it with the following code:

random.shuffle(days)

The sequence is shuffled in-place, so we would have to print it if we wanted to see the result:

days
['Monday', 'Friday', 'Wednesday', 'Sunday', 'Saturday', 'Tuesday', 'Thursday']

Trying to shuffle an immutable sequence will return an error message. For example, if we start from a tuple:

a = ("A", "B", "C")

...trying to shuffle it generates an error:

try:
    random.shuffle(a)
except:
    print("Error")
Error

If a complex structure is passed to this function -such as a NumPy array, for example- the results are not as expected:

import numpy as np
a = np.arange(9).reshape(3, 3)
a
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
random.shuffle(a)
a
array([[0, 1, 2],
       [3, 4, 5],
       [0, 1, 2]])
Submitted by admin on Fri, 03/12/2021 - 09:00