Shuffle a List in Python
In Python, you can shuffle a list using the shuffle()
function from the random
module. It modifies the list in place and doesn’t return a new list.
import random
my_list = [1, 2, 3, 4, 5]
random.shuffle(my_list)
print(my_list) # Output: [1, 5, 2, 4, 3]
If you need to create a new shuffled list without modifying the original list, you can use random.sample()
.
import random
my_list = [1, 2, 3, 4, 5]
shuffled_list = random.sample(my_list, len(my_list))
print(shuffled_list) # Output: [4, 3, 1, 2, 5]
Shuffle a list with seed value
Using a seed ensures that you get the same “random” sequence of shuffles every time you run the code with the same seed value. It is useful for recreating the exact shuffled order for testing, debugging, simulations, or scientific experiments.
import random
# Set the seed
random.seed(30)
my_list = [1, 2, 3, 4, 5]
# Shuffle the list
random.shuffle(my_list)
print(my_list) # Output: [2, 1, 4, 3, 5]
Similarly, using the same seed with random.sample()
will produce the same shuffled result each time the code is run.
import random
# Set the seed
random.seed(40)
my_list = [1, 2, 3, 4, 5]
# Shuffle the list
shuffled_list = random.sample(my_list, len(my_list))
print(shuffled_list) # Output: [4, 1, 5, 2, 3]