How to Shuffle a List in Python

Contents
In this article, you will learn how to shuffle a list in Python.
How to shuffle a list
To shuffle a list in Python, you can use the built-in shuffle() function from the random module. Here’s an example:
import random
my_list = [1, 2, 3, 4, 5]
random.shuffle(my_list)
print(my_list)
# Output: [2, 5, 1, 4, 3]
In the example above, we first import the random module. Then, we create a list my_list containing the integers from 1 to 5. Finally, we use the shuffle() function from the random module to shuffle the elements in the list, and print the shuffled list.
Here are some additional details about shuffling a list in Python:
- The shuffle() function shuffles the list in-place, which means that it modifies the original list rather than creating a new one. So, make sure you don’t need the original order of the list before shuffling it.
- The shuffle() function can be used with any type of list, not just integers. You can shuffle lists containing strings, objects, or any other data type.
-
If you want to shuffle a list without modifying the original list, you can make a copy of the list and shuffle the copy instead. Here’s an example:
import random my_list = [1, 2, 3, 4, 5] shuffled_list = my_list.copy() random.shuffle(shuffled_list) print(my_list) # original list is unchanged print(shuffled_list) # shuffled list # Output: # [1, 2, 3, 4, 5] # [5, 3, 1, 4, 2]
-
If you need to shuffle a list multiple times, you can use the shuffle() function repeatedly. For example:
import random my_list = [1, 2, 3, 4, 5] random.shuffle(my_list) print(my_list) # shuffled list random.shuffle(my_list) print(my_list) # shuffled again # Output: # [2, 4, 1, 5, 3] # [4, 5, 1, 2, 3]