The random.shuffle()
function in the random module rearranges items in a sequence in random order. It perform the re-arrangement in-place meaning that the original sequence is changed.
You should note that sets and dictionaries are not sequences while tuples and strings are immutable and consequently unsubscriptible thus we are only left with the lists and user-defined objects that are mutable.
shuffle(seq)
seq |
The mutable sequence(mostly a list) to shuffle. |
The function does not return any value; it simply shuffles the given sequence in place. All items are equally likely to occur in any given position in the shuffled sequence.
Since the function changes the original list, you might need to keep a copy of the list before calling the function on the list.
Shuffling other sequence data types
As we have seen above, it is impossible to use the shuffle method on other builtin types except lists. However, we can simply cast the data types that we want to shuffle into a list, shuffle it and then turn it back into the respective type.