Sling Academy
Home/Python/Shuffling a List in Python (4 Approaches)

Shuffling a List in Python (4 Approaches)

Last updated: June 16, 2023

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!

Next Article: Python: 3 Ways to Find the Product of a Numeric List

Previous Article: Python: Checking If a List Contains an Element (3 Approaches)

Series: Python List Tutorials (Basic and Advanced)

Python

You May Also Like

  • Python TypeError: write() argument must be str, not bytes
  • 4 ways to install Python modules on Windows without admin rights
  • Python TypeError: object of type ‘NoneType’ has no len()
  • Python: How to access command-line arguments (3 approaches)
  • Understanding ‘Never’ type in Python 3.11+ (5 examples)
  • Python: 3 Ways to Retrieve City/Country from IP Address
  • Using Type Aliases in Python: A Practical Guide (with Examples)
  • Python: Defining distinct types using NewType class
  • Using Optional Type in Python (explained with examples)
  • Python: How to Override Methods in Classes
  • Python: Define Generic Types for Lists of Nested Dictionaries
  • Python: Defining type for a list that can contain both numbers and strings
  • Using TypeGuard in Python (Python 3.10+)
  • Python: Using ‘NoReturn’ type with functions
  • Type Casting in Python: The Ultimate Guide (with Examples)
  • Python: Using type hints with class methods and properties
  • Python: Typing a function with default parameters
  • Python: Typing a function that can return multiple types
  • Python: Typing a function with *args and **kwargs