Shuffling a List in Python (4 Approaches)

Updated: June 16, 2023 By: Goodman Post a comment

Shuffling a list is useful for randomizing the order of elements, which can be beneficial in scenarios like creating unpredictable game sequences, conducting surveys with randomized questions, or ensuring fairness in selecting items from a list.

This succinct example-based article will walk you through a couple of different ways to shuffle a given list in Python. We’ll also discuss the performance of each approach so you’ll gain some information about how efficient it is.

Using the random.shuffle() function

Theshuffle() function from the random module can randomly reorder the elements of a list in place. It does not return a new list but modifies the original list.

Example:

# Import random module
import random

# Define a list
my_list = [1, 2, 3, 4, 5]

# Shuffle the list using random.shuffle() function
random.shuffle(my_list)

# Print the result
print(my_list)

You can also specify a seed for reproducibility or testing purposes, like this:

# Import random module
import random

# Set the seed to 2023
random.seed(2023)

# Define a list
my_list = [1, 2, 3, 4, 5]

# Shuffle the list using random.shuffle() function
random.shuffle(my_list)

# Print the result
print(my_list)
# Output: [1, 3, 2, 5, 4]

Performance: This solution has a time complexity of O(n), where n is the length of the list. This is because it iterates over the list and swaps each element with a random element. The space complexity is O(1) because it does not create any extra variables or data structures.

Using the random.sample() function

In case you want to keep the original list intact, you can use the random.sample() function instead of the random.shuffle() function. It creates a new list that contains a random sample of the elements of the original list without replacement.

Example:

import random

my_list = [1, 2, 3, 4, 5]
shuffled_list = random.sample(my_list, len(my_list))
print(shuffled_list)

Like in the preceding approach, you can use a seed to get the same result each time executing the code.

Performance: Using random.sample() creates a new list and has a time complexity of O(n). (similar to random.shuffle()). However, it requires additional memory to store the new list.

Using the sorted() function and a custom key

The main idea of this approach is to use the sorted() function and a custom key function to create a new list that contains the elements of the original list sorted in random order. The custom key function uses the random.random() function from the random module to generate a random number for each element and use it as the sorting criterion. It does not modify the original list but returns a new list.

Example:

import random

random.seed(2023)

my_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
shuffled_list = sorted(my_list, key=lambda x: random.random())
print(shuffled_list)

Output:

['g', 'h', 'd', 'f', 'a', 'e', 'c', 'b']

This approach is more verbose but less efficient than the earlier ones.

Using the Fisher-Yates algorithm

The Fisher-Yates algorithm is a classic algorithm for shuffling a list or an array. It works by iterating over the list from the last element to the first and swapping each element with a random element from the remaining unshuffled part of the list.

Example:

import random

my_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']

for i in range(len(my_list) - 1, 0, -1):
    j = random.randint(0, i)
    my_list[i], my_list[j] = my_list[j], my_list[i]
print(my_list)

My output (yours might be different from mine due to the randomness and seedlessness):

['h', 'f', 'b', 'e', 'c', 'a', 'g', 'd']

This solution is not very intuitive or easy to understand for beginners or people who are not familiar with the algorithm. The amount of code that needs to be written is far more than the first and the second approaches (but the performance is similar).

Conclusion

We’ve seen more than one way to randomly reorder a list in Python. Choose from them the one that suits your scenario to go with. If you have any questions, please comment. Happy coding & have a nice day!