Skip to content

Python: Shuffle a List (Randomize Python List Elements)

Python Shuffle a List Cover Image

In this tutorial, you’ll learn how to use Python to shuffle a list, thereby randomizing Python list elements. For this, you will learn how to use the Python random library, in particular the .shuffle() and .random() methods.

Knowing how to shuffle a list and produce a random result is an incredibly helpful skill. For example, it can be incredibly helpful in developing a Python game where you need to choose a random result. It can also have immensely helpful applications in data-related work, where you may need to pull random results.

The Quick Answer: Use random.shuffle()

Quick Answer - Shuffle a Python List

What is the Difference Between .shuffle and .sample?

Python comes built-in with an incredibly helpful library to generate randomness, called random. Throughout this tutorial, you’ll learn how to use the random.shuffle() and random.sample() functions. Before we dive into how to use them, however, let’s quickly explore what the differences are.

Both functions return a list that is randomly sorted, but how they return them is different:

  • random.shuffle() shuffles the original list, meaning the shuffling can be done in-place
  • random.sample() returns a new shuffled list, based on the original list

random.sample() can also be used to shuffle strings and tuples, as it creates a new list, thereby allowing you to work on immutable data types.

Now, let’s dive into how to shuffle a list in Python!

Check out some other Python tutorials on datagy, including our complete guide to styling Pandas and our comprehensive overview of Pivot Tables in Pandas!

Shuffle a Python List and Re-assign It to Itself

The random.shuffle() function makes it easy to shuffle a list’s items in Python. Because the function works in-place, we do not need to reassign the list to itself, but it allows us to easily randomize list elements.

Let’s take a look at what this looks like:

# Shuffle a list using random.shuffle()
import random

a_list = ['welcome', 'to', 'datagy', 'where', 'you', 'will', 'learn', 'Python', 'and', 'more']
random.shuffle(a_list)

print(a_list)
# Returns: ['more', 'will', 'Python', 'welcome', 'learn', 'you', 'where', 'to', 'datagy', 'and']

What we’ve done here is:

  1. Create a new list
  2. Applied the random.shuffle() function to it
  3. Printed the result to verify the shuffling

Keep in mind, if you’re following along with the example above, your randomly sorted list will probably look different!

In the next section, you’ll learn how to use the random.sample() function to randomize a list in Python.

Want to learn more about Python list comprehensions? Check out this in-depth tutorial that covers off everything you need to know, with hands-on examples. More of a visual learner, check out my YouTube tutorial here.

Shuffle a Python List and Assign It to a New List

The random.sample() function is used to sample a set number of items from a sequence-like object in Python. The function picks these items randomly.

Let’s take a quick look at what the function looks like:

random.sample(iterable, k)

In this case, the iterable will be the list we want to shuffle, and k refers to the number of items we want to select. Because we want to return the full list in a random order, we will pass in the length of the list into the k parameter.

Let’s take a look at how we can use the .sample() function to randomize a Python list:

# Shuffle a list using random.sample()
import random

a_list = ['welcome', 'to', 'datagy', 'where', 'you', 'will', 'learn', 'Python', 'and', 'more']
shuffled = random.sample(a_list, len(a_list))

print(shuffled)
# Returns: ['where', 'you', 'welcome', 'to', 'more', 'Python', 'and', 'datagy', 'will', 'learn']

Let’s take a look at how we’ve managed to randomize our Python list elements:

  1. We generated our list and assigned it to a_list
  2. We generated a new variable shuffled which took the random.sample() function. We passed the list and the length of our list into the function. By using the len() function, we are able to keep this method dynamic, as the length of the list may change.

In the next section, you’ll learn how to reproduce a shuffled list result in Python.

Want to learn how to pretty print a JSON file using Python? Learn three different methods to accomplish this using this in-depth tutorial here.

Reproduce a Shuffled Python List Result

When working with random results, there may be times when you want to be able to reproduce a result. In this example below, you’ll learn how to be able to reproduce a shuffled list.

We will use the random.seed() function to generate a result that is reproducible.

Let’s take a look at what this looks like:

# Reproducing a randomly shuffled list in Python
import random

a_list = ['welcome', 'to', 'datagy', 'where', 'you', 'will', 'learn', 'Python', 'and', 'more']

random.seed(1)

for i in range(5):
    random.shuffle(a_list)
    print(a_list)

# Returns:
# ['learn', 'and', 'more', 'Python', 'will', 'where', 'welcome', 'you', 'to', 'datagy']
# ['will', 'to', 'more', 'welcome', 'where', 'datagy', 'learn', 'you', 'and', 'Python']
# ['you', 'and', 'learn', 'Python', 'datagy', 'will', 'more', 'to', 'welcome', 'where']
# ['to', 'learn', 'welcome', 'and', 'datagy', 'you', 'will', 'where', 'Python', 'more']
# ['welcome', 'to', 'datagy', 'more', 'will', 'where', 'learn', 'you', 'and', 'Python']

Now, it may look like the resulting printed lists aren’t random. However, if we were to re-run our program above, the program would return the same randomly shuffled lists each time! The random.seed() function allows us generate a base value that defines the pseudo-randomness of the functions that follow it. Because, in this case, we assigned it a specific value of 2, we are able to reproduce the randomness.

In the next section, you’ll learn how to shuffle a Python list of lists.

Want to learn more about Python for-loops? Check out my in-depth tutorial that takes your from beginner to advanced for-loops user! Want to watch a video instead? Check out my YouTube tutorial here.

Shuffle a Python List of Lists

In Python, you’ll often encounter multi-dimensional lists, often referred to as lists of lists. We can easily do this using a for loop. By looping over each list in the list of lists, we can then easily apply the random.shuffle() function to randomize each sublist’s elements.

Let’s take a look at what this looks like:

# Shuffling a list of lists in Python
import random

a_list = [['apple', 'orange', 'grape'], ['banana', 'melon', 'tangerine'], ['lime', 'lemon', 'strawberry']]

for sublist in a_list:
    random.shuffle(sublist)

print(a_list)

# Returns: [['grape', 'orange', 'apple'], ['melon', 'banana', 'tangerine'], ['strawberry', 'lemon', 'lime']]

While we could also accomplish this using a list comprehension, the syntax of not re-assigning the list comprehension is a bit awkward and not as intuitive. For this reason, we’ve opted to use a for loop here as we should always be striving for readability.

In the next section, you’ll learn how to shuffle multiple lists with the same order of shuffling.

Want to learn how to use the Python zip() function to iterate over two lists? This tutorial teaches you exactly what the zip() function does and shows you some creative ways to use the function.

Shuffle Multiple Lists with the Same Order of Shuffling

Let’s say you have two lists: one that contains the type of fruit and the other the number of that type of fruit you have. You want to shuffle the lists but you want the referential integrity to remain true (meaning that index 0 of both lists would be shuffled to the same index in the shuffled result).

In order to accomplish this, we’ll:

  1. Merge the two lists in a list of lists using the zip() function
  2. Shuffle the list of lists internally
  3. Unpack the list of lists into individual lists

Let’s take a look at how we can do this:

# Shuffling two lists in the same order
import random

fruits = ['apples', 'grapes', 'oranges', 'bananas']
quantities = [50, 40, 60, 70]

merged = list(zip(fruits, quantities))
# This looks like: [('apples', 50), ('grapes', 40), ('oranges', 60), ('bananas', 70)]

random.shuffle(merged)

fruits = [item[0] for item in merged]
quantities = [item[1] for item in merged]

print(fruits)
print(quantities)

# Returns:
# ['bananas', 'oranges', 'apples', 'grapes']
# [70, 60, 50, 40]

We can see that we’ve made good use of both the zip() function as well as Python list comprehensions to make this happen.

Need to automate renaming files? Check out this in-depth guide on using pathlib to rename files. More of a visual learner, the entire tutorial is also available as a video in the post!

Conclusion

In this tutorial, you learned how to use Python to randomly shuffle a list, thereby sorting its items in a random order. For this, you learned how to use the Python random library, in particular the .shuffle() and .random() methods.

To learn more about the random library, check out the official documentation here.

Nik Piepenbreier

Nik is the author of datagy.io and has over a decade of experience working with data analytics, data science, and Python. He specializes in teaching developers how to use Python for data science using hands-on tutorials.View Author posts

1 thought on “Python: Shuffle a List (Randomize Python List Elements)”

  1. Pingback: Python: Select Random Element from a List • datagy

Leave a Reply

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