# 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
• Initialize the random number generator with `random.seed()`

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

## `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)
# [1, 0, 4, 3, 2]
``````

## `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 article 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)
# [0, 3, 1, 4, 2]

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

## 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)
# bedca
``````

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

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

## Initialize the random number generator with `random.seed()`

You can initialize a random number generator with `random.seed()`.

After initializing with the same seed, it is shuffled in the same way.

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

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