note.nkmk.me

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

Posted: 2020-02-05 / Tags: Python, List

To randomly shuffle elements of lists (list), strings (str) and tuples (tuple) in Python, use the random module.

random provides shuffle() that shuffles the original list in place, and sample() that returns a new list that is randomly shuffled. sample() can also be used for strings and tuples.

  • random.shuffle() shuffles the original list
  • random.sample() returns a new shuffled list
  • Shuffle strings and tuples
  • Set a seed

If you want to sort in ascending or descending order or reverse instead of shuffling, see the following posts.

Sponsored Link

random.shuffle() shuffles the original list

The original list can be shuffled in place by using random.shuffle().

import random

l = list(range(5))
print(l)
# [0, 1, 2, 3, 4]

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

random.sample() returns a new shuffled list

random.sample() returns a new shuffled list. The original list remains unchanged.

random.sample() returns random elements from a list. Pass the list to the first argument and the number of elements to return to the second argument. See the following post for details.

By setting the total number of elements in the list to the second argument, random.sample() returns a new list with all elements randomly shuffled. The total number of elements in the list can be obtained with len().

l = list(range(5))
print(l)
# [0, 1, 2, 3, 4]

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

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

Shuffle strings and tuples

Strings and tuples are immutable, so using random.shuffle() to modify the original object will raise an error TypeError.

s = 'abcde'

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

t = tuple(range(5))
print(t)
# (0, 1, 2, 3, 4)

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

To shuffle strings or tuples, use random.sample() which creates a new object.

random.sample() returns a list even when a string or tuple is specified to the first argument, so it is necessary to covert it to a string or tuple.

For strings, a list of characters is returned. Use the join() method to concatenate to a single string again.

sr = ''.join(random.sample(s, len(s)))
print(sr)
# caebd

For tuples, use tuple(), which creates a tuple from a list.

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

Set a seed

By giving an arbitrary integer to random.seed(), the seed for generating random numbers can be set.

random.seed(0)
l = list(range(5))
random.shuffle(l)
print(l)
# [2, 1, 0, 4, 3]
Sponsored Link
Share

Related Categories

Related Posts