Python Random shuffle() Method

Usage

The random.shuffle() method is used to randomly reorder the items of a mutable sequence in-place.

Mutable sequences include lists, but not sets or dictionaries. Sets and dictionaries are mutable, but they are unordered collections, so the concept of “reordering” does not apply to them.

Keep in mind that the random.shuffle() method does not return a new sequence; rather, it modifies the original sequence in-place.

Syntax

random.shuffle(x)

ParameterConditionDescription
xRequiredA mutable sequence that you want to shuffle.

Module Import

To use random.shuffle(), you’ll first need to import the random module.

import random

Examples

Let’s see how the random.shuffle() function works in practice. Suppose you have a list of numbers like this:

import random

numbers = [1, 2, 3, 4, 5]
random.shuffle(numbers)
print(numbers)
# Possible output: [2, 3, 5, 1, 4]

Notice that the shuffle() method did not return a new list; instead, it modified the existing list in-place.

If you want to get a shuffled copy of your list while keeping the original intact, you can use the random.sample() function:

numbers = [1, 2, 3, 4, 5]
shuffled_copy = random.sample(numbers, len(numbers))

print(numbers)         # Output: [1, 2, 3, 4, 5]
print(shuffled_copy)   # Possible output: [4, 1, 3, 5, 2]

Shuffling an Immutable Sequence

The shuffle() function is specifically designed to work with mutable sequences like lists. You cannot directly use it with immutable sequences like strings or tuples. Attempting to do so will result in a TypeError.

numbers = (1, 2, 3, 4, 5)
random.shuffle(numbers)
# TypeError: 'tuple' object does not support item assignment

If you need to shuffle an immutable sequence, you should use the random.sample() function to create a new shuffled list of elements, and then convert that list back into your desired data type.

Here’s an example with a tuple:

numbers = (1, 2, 3, 4, 5)
shuffled_list = random.sample(numbers, len(numbers))  # Create a shuffled list
shuffled_copy = tuple(shuffled_list)                  # Convert back to a tuple

print(shuffled_copy)
# Output will be a shuffled tuple, e.g., (3, 4, 5, 1, 2)