Shuffle a List, String, Tuple in Python: random.shuffle, sample
In Python, you can shuffle (i.e., randomly reorder) sequences using random.shuffle() and random.sample().
While random.shuffle() modifies a list in place, random.sample() returns a new randomized list and also supports immutable types such as strings and tuples.
For information on sorting or reversing a list, refer to the following articles.
- Sort a List, String, Tuple in Python: sort, sorted
- Reverse a List, String, Tuple in Python: reverse, reversed
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 containing randomly selected elements from a list. The original list remains unchanged.
To create a fully shuffled list, pass the total number of elements 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() to generate a list of randomly ordered elements, then convert it back to the original type.
When used on a string, random.sample() returns a list of characters. Use the join() method to convert it back into a string.
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 an individual string or tuple. If you have a list of strings or tuples, you can use random.sample() or random.shuffle() to shuffle the list.
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().
Setting the same seed ensures that the shuffle produces the same result each time, which is useful for reproducibility.
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]