ExampleEdit & Run

Use the shuffle() function

#import the random module
import random

#The list to shuffle
my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

#shuffle the list in-place
random.shuffle(my_list)

print(my_list)
Output:
[7, 2, 8, 3, 9, 6, 4, 5, 0, 1][Finished in 0.012169611873105168s]

The random.shuffle() function in the  random module rearranges items in a sequence in random order. It perform the re-arrangement in-place meaning that the original sequence is changed.

You should note that sets and dictionaries are not sequences while tuples and strings are immutable and consequently unsubscriptible thus we are only left with the lists and user-defined objects that are mutable.

Syntax:
shuffle(seq)
seq The mutable sequence(mostly a list) to shuffle.
Parameters:

The function does not return any value; it simply shuffles the given sequence in place. All items are equally likely to occur in any given position in the shuffled sequence.

ExampleEdit & Run

Shuffle a list

#import the random module
import random

L = [i for i in range(10, 20)]

random.shuffle(L)

print(L)
Output:
[18, 17, 16, 13, 14, 19, 10, 11, 12, 15][Finished in 0.011851952178403735s]

Since the function changes the original list, you might need to keep a copy of the list before calling the function on the list.

ExampleEdit & Run
import random

list_original = [1, 2, 3, 4, 5] 

list_copy = list(list_original) 

random.shuffle(list_copy)

print('original: ', list_original)
print('shuffled: ', list_copy)
Output:
original:  [1, 2, 3, 4, 5]shuffled:  [4, 2, 3, 5, 1][Finished in 0.011769118020310998s]

Shuffling other sequence data types

As we have seen above, it is impossible to use the shuffle method on  other builtin types except lists. However, we can simply cast the data types that we want to shuffle into a list, shuffle it and then turn it back into the respective type.

ExampleEdit & Run

Shuffle a tuple

import random

my_tuple = (1, 2, 3, 4, 5, 6)

L = list(my_tuple)

random.shuffle(L)

shuffled_tuple = tuple(L)

print('original: ', my_tuple)
print('shuffled: ', shuffled_tuple)
Output:
original:  (1, 2, 3, 4, 5, 6)shuffled:  (1, 3, 5, 2, 6, 4)[Finished in 0.011162206996232271s]
ExampleEdit & Run

shuffle a string

import random

my_string = "Hello, World!"

L = list(my_string)

random.shuffle(L)

shuffled_string = ''.join(L)

print('original: ', my_string)
print('shuffled: ', shuffled_string)
Output:
original:  Hello, World!shuffled:  rdH,o o!elWll[Finished in 0.011037347838282585s]