How To Shuffle A List In Python

Working with lists is a fundamental aspect of programming in Python, and one among their many useful operations is the ability to shuffle the elements.

This is especially beneficial in cases where you need to randomize the order of items for tasks like simulations, games, or machine learning algorithms. In this tutorial, we will learn how to shuffle a list in Python using different techniques.

We will explore two primary methods: shuffling using the Fisher-Yates algorithm and using Python’s in-built random.shuffle() function.

Method 1: Using the Fisher-Yates Algorithm

The Fisher-Yates algorithm, also known as the Knuth shuffle, is a widely-used method for shuffling lists. This algorithm works by iterating through the list from the last element to the first and swapping the current element with a random element from the remaining unshuffled elements.

Here’s how to implement the Fisher-Yates algorithm for shuffling a list in Python:

  1. Import the random module.
  1. Define the fisher_yates_shuffle function.
  1. Create a list and call the fisher_yates_shuffle function with it.

The output will display the original list and the shuffled list.

Method 2: Using Python’s random.shuffle() function

Another more straightforward method to shuffle a list in Python is by using the built-in random.shuffle() function. The random.shuffle() function takes a sequence (like a list) as an argument and shuffles its elements in-place.

Here’s how to use the random.shuffle() function:

  1. Import the random module.
  1. Create a list.
  1. Shuffle the list using random.shuffle()

The output will display the original list and the shuffled list.

Full code:

Here’s the full code for both methods:

Output:

Original list using Fisher-Yates: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Shuffled list using Fisher-Yates: [5, 2, 4, 6, 3, 1, 9, 0, 7, 8]

Original list using random.shuffle(): [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Shuffled list using random.shuffle(): [8, 7, 6, 9, 0, 1, 2, 5, 4, 3]

Conclusion:

In this tutorial, we learned how to shuffle a list in Python using two methods: the Fisher-Yates algorithm and the built-in random.shuffle() function. Both methods are reliable choices for your applications, so choose the one that best fits your needs or preferences.

The Fisher-Yates algorithm might be useful in cases where you want to customize or understand the shuffling process, while the random.shuffle() function offers an easy-to-use, ready-made solution.