[Beginner’s Guide] How to Shuffle a List in Python

Shuffling a list is a common operation in Python programming, especially when working with data analysis, machine learning, or game development. Shuffling means changing the order of the elements in a list randomly, so that each possible permutation is equally likely. This can be useful for creating randomness, sampling data, or testing algorithms.

There are different ways to shuffle a list in Python, each with advantages and disadvantages. In this post, we will explore two of the most common methods: random.shuffle() and random.sample(). We will also briefly mention some advanced techniques for shuffling large or complex lists. By the end of this post, you will be able to shuffle any list in Python with ease and confidence.

Option 1: random.shuffle()

The random.shuffle() function is part of the random module in the standard library. It takes a list as an argument and shuffles it in-place, meaning that it modifies the original list and does not return a new one. Here is an example of how to use it:

# Import the random module
import random

# Create a list of numbers
numbers = [1, 2, 3, 4, 5]

# Print the original list
print("Original list:", numbers)

# Shuffle the list using random.shuffle()
random.shuffle(numbers)

# Print the shuffled list
print("Shuffled list:", numbers)
Original list: [1, 2, 3, 4, 5]
Shuffled list: [4, 2, 5, 3, 1]

As you can see, the order of the elements in the list has changed randomly. Note that each time you run the code, you will get a different output, as the shuffling is unpredictable.

One thing to remember when using random.shuffle() is that it shuffles the original list in-place. This means that if you need to preserve the original order of the list for some reason, you will lose it after shuffling.

For example, if you have a list of names and you want to shuffle them for a lottery draw, but you also want to keep the original alphabetical order for reference, you will need to make a copy of the list before shuffling it. Here is how to do that:

# Import the random module
import random

# Create a list of names
names = ["Alice", "Bob", "Charlie", "David", "Eve"]

# Make a copy of the list using slicing
names_copy = names[:]

# Print the original list and its copy
print("Original list:", names)
print("Copy of the list:", names_copy)

# Shuffle the copy using random.shuffle()
random.shuffle(names_copy)

# Print the shuffled copy
print("Shuffled copy:", names_copy)
Original list: ['Alice', 'Bob', 'Charlie', 'David', 'Eve']
Copy of the list: ['Alice', 'Bob', 'Charlie', 'David', 'Eve']
Shuffled copy: ['David', 'Alice', 'Eve', 'Charlie', 'Bob']

As you can see, we have used slicing to create a copy of the list before shuffling it. This way, we can shuffle the copy without affecting the original. Slicing is a technique that allows us to extract a portion of a list by specifying its start and end indices. By leaving out both indices, we get the entire list as a new object.

Option 2: random.sample()

Another way to shuffle a list in Python is to use the random.sample() function.

This function also belongs to the random module and takes two arguments: a population and a sample size. It returns a new list that contains a random sample of elements from the population, without replacement. This means that each element can only be selected once and that the sample size cannot be larger than the population size.

The random.sample() function can be used to create a new shuffled list by passing the original list as the population and its length as the sample size. Here is an example of how to use it:

# Import the random module
import random

# Create a list of colors
colors = ["red", "green", "blue", "yellow", "pink"]

# Print the original list
print("Original list:", colors)

# Create a new shuffled list using random.sample()
shuffled_colors = random.sample(colors, len(colors))

# Print the new shuffled list
print("New shuffled list:", shuffled_colors)
Original list: ['red', 'green', 'blue', 'yellow', 'pink']
New shuffled list: ['pink', 'green', 'red', 'blue', 'yellow']

As you can see, we have created a new shuffled list by passing colors as the population and len(colors) as the sample size. The len() function returns the number of elements in a list, so we are essentially asking for a sample that contains all the elements of the original list, in a random order.

One of the benefits of using random.sample() is that it does not modify the original list, but creates a new one. This means that we do not need to make a copy of the list before shuffling it, as we did with random.shuffle(). However, this also means that we need to assign the result of the function to a new variable, otherwise we will lose it.

Bonus Options:

The random.shuffle() and random.sample() functions are the most common and convenient ways to shuffle a list in Python, but they are not the only ones. Some advanced techniques can be used for shuffling large or complex lists, such as:

  • The Fisher-Yates shuffle algorithm, which is a more efficient and secure way to shuffle a list in-place.
    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 ones. You can implement this algorithm using a for loop and the random.randint() function, which returns a random integer between two given values.
  • The Numpy library, which is a popular tool for scientific computing in Python.
    It offers a variety of functions and methods for working with arrays, which are similar to lists but more powerful and efficient. One of the methods is numpy.random.shuffle(), which shuffles an array in-place, just like random.shuffle(). Another method is numpy.random.permutation(), which returns a new shuffled array, just like random.sample().

Conclusion:

Shuffling a list is a useful and fun operation in Python programming.

In this post, we have learned two of the most common ways to shuffle a list in Python: random.shuffle() and random.sample(). We have also briefly mentioned some advanced techniques for shuffling large or complex lists. We hope you have enjoyed this post and learned something new.

Now it’s your turn to try out these methods and share your experiences with us. What are some of the applications or projects that you have used or would like to use shuffling for? What other topics would you like to see covered in future posts? Let us know in the comments below.

References:

Stephen Mclin
Stephen Mclin

Hey, I'm Steve; I write about Python and Django as if I'm teaching myself. CodingGear is sort of like my learning notes, but for all of us. Hope you'll love the content!

Articles: 125

Leave a Reply

Your email address will not be published. Required fields are marked *