Shuffle a list, string, tuple in Python (random.shuffle, sample)

Modified: | Tags: Python, List

In Python, you can shuffle (i.e., randomize) a list with random.shuffle() and random.sample().

random.shuffle() shuffles a list in place, and random.sample() returns a new randomized list. random.sample() is also applicable to immutable data types, such as strings and tuples.

For information on sorting or reversing a list, refer to the following articles.

Shuffle a list in place: random.shuffle()

You can shuffle a list in place with random.shuffle().

import random

l = [0, 1, 2, 3, 4]

random.shuffle(l)
print(l)
# [0, 3, 2, 4, 1]

Create a new shuffled list: random.sample()

random.sample() returns a new list with selected random elements from a list. The original list is not changed.

To create a new list with all elements randomly shuffled, set the total number of elements in the list as the second argument. You can find the total number of elements using len().

import random

l = [0, 1, 2, 3, 4]

l_shuffled = random.sample(l, len(l))
print(l_shuffled)
# [4, 3, 0, 1, 2]

print(l)
# [0, 1, 2, 3, 4]

Shuffle a string and tuple

Since strings and tuples are immutable, using random.shuffle() on them will result in a TypeError.

import random

s = 'abcde'

# random.shuffle(s)
# TypeError: 'str' object does not support item assignment

t = (0, 1, 2, 3, 4)

# random.shuffle(t)
# TypeError: 'tuple' object does not support item assignment

To shuffle a string or tuple, use random.sample(), which creates a new object.

Note that random.sample() returns a list, even when provided with a string or tuple. Thus, the resulting list must be converted back into the desired data type.

When used with a string, random.sample() returns a list of characters. To convert this back into a string, use the join() method.

s_shuffled = ''.join(random.sample(s, len(s)))
print(s_shuffled)
# aedcb

To convert a list back into a tuple, use tuple().

t_shuffled = tuple(random.sample(t, len(l)))
print(t_shuffled)
# (4, 1, 2, 0, 3)

The above examples demonstrate how to shuffle a string or tuple itself. If you want to deal with a list of strings or tuples, you can use random.sample() and random.shuffle() for shuffling.

l = ['apple', 'banana', 'cherry', 'date']

l_shuffled = random.sample(l, len(l))
print(l_shuffled)
# ['cherry', 'banana', 'apple', 'date']

random.shuffle(l)
print(l)
# ['date', 'apple', 'cherry', 'banana']

Fix the random seed: random.seed()

You can fix the random seed and initialize the random number generator with random.seed().

Initializing with the same seed will produce the same shuffle pattern.

l = [0, 1, 2, 3, 4]
random.seed(0)
random.shuffle(l)
print(l)
# [2, 1, 0, 4, 3]

l = [0, 1, 2, 3, 4]
random.seed(0)
random.shuffle(l)
print(l)
# [2, 1, 0, 4, 3]

Related Categories

Related Articles