How to Shuffle a List of Python Objects?

You’ve got a Python list and you want to randomly reorder all elements? No problem, use the shuffle function in Python’s random library. Here’s some code to show you how to do this:

import random

a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

random.shuffle(a)
print(a)
# [6, 8, 5, 7, 2, 3, 9, 1, 4, 0]

random.shuffle(a)
print(a)
# [8, 4, 9, 2, 6, 3, 5, 7, 0, 1]

random.shuffle(a)
print(a)
# [1, 0, 7, 2, 4, 9, 5, 8, 3, 6]

random.shuffle(a)
print(a)
# [4, 6, 0, 5, 1, 3, 9, 2, 7, 8]

As the elements are randomly reordered, the result will look different when you’ll execute the same code snippet. Like any random function, the behavior is non-deterministic. Please also note that the list itself is shuffled—there’s no new list created.

Leave a Comment

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