random.shuffle(x)
The random.shuffle function shuffles the sequence x in-place.
If you want to shuffle an immutable sequence x, you can use:
- x: Sequence to shuffle. It must be mutable because, in any other case, the function will return an error.
The random.shuffle function returns the sequence x passed as an argument shuffled.
If we have a list made up of the names of the days of the week:
...we could shuffle it with the following code:
The sequence is shuffled in-place, so we would have to print it if we wanted to see the result:
Trying to shuffle an immutable sequence will return an error message. For example, if we start from a tuple:
...trying to shuffle it generates an error:
random.shuffle(a)
except:
print("Error")
If a complex structure is passed to this function -such as a NumPy array, for example- the results are not as expected:
a
[3, 4, 5],
[6, 7, 8]])
a
[3, 4, 5],
[0, 1, 2]])