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)
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.
shuffle(seq)
seq |
The mutable sequence(mostly a list) to shuffle. |
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.
Shuffle a list
#import the random module
import random
L = [i for i in range(10, 20)]
random.shuffle(L)
print(L)
Since the function changes the original list, you might need to keep a copy of the list before calling the function on the list.
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)
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.
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)
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)