In this post, you can learn several examples about how to randomize lists in Python, function random.shuffle() and how to shuffle two list in similar way. All the examples are tested against Python 3.7.

Some of the examples include free shuffling, synchronized shuffling of several lists with seed, shuffling different types of lists. The examples are for beginners to advanced and include full code and results:

You may like also: Python Random Number Examples

## Function random.shuffle()

The official documentation describe the function as:

random.shuffle(x[, random])

Shuffle the sequence x in place.
The optional argument random is a 0-argument function returning a random float in [0.0, 1.0]; by default, this is the function random().
To shuffle an immutable sequence and return a new shuffled list, use sample(x, k=len(x)) instead.

The syntax is simple and the usage of the function is straightforward. There are few arguments:

• x is any sequence(list, String or tuple) you want to shuffle.
• Optional argument random is a 0-argument function returning a random float number between 0.1 to 1.0. By default, this is the function random().

## Python shuffle list of numbers / range

Shuffling a list in Python the numbers from 0 to 20 (exclusive 20) generated by range. Generating list of numbers with ranges is a common operation in Python. The only disadvantage is that they are sorted. If you want to shuffle the list in random order you can use random.shuffle :

``````import random
nums = [x for x in range(20)]
random.shuffle(nums)
print(nums)
``````

result:

``````[9, 15, 19, 16, 8, 17, 10, 1, 14, 4, 18, 13, 0, 5, 12, 3, 7, 11, 6, 2]
``````

Repeating the shuffle will produce different result each time unless we use a seed.

## Python shuffle list of numbers

Shuffling a list in python the numbers from predefined list. The example is identical to the previous one:

``````import random
nums = [0, 5, 7, 4, 6, 8, 3]
random.shuffle(nums)
print(nums)
``````

result:

``````[5, 8, 4, 7, 3, 0, 6]
``````

## Python shuffle list of strings

The same way can be applied for list of strings. All you need to do is use method - random.shuffle:

``````import random
str = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
random.shuffle(str)
print(str)
``````

result:

``````['f', 's', 'c', 'x', 'a', 'l', 'n', 'z', 'e', 'r', 'j', 'v', 'w', 'g', 'm', 'u', 'k', 'd', 'i', 'p', 'h', 'q', 'y', 'b', 't', 'o']
``````

If you want to sort the shuffled list you have two options:

• change the list
``````str.sort()
``````
• keep the original list
``````for x in sorted(str):
print x
``````

## Python synchronized shuffle of two lists

Sometimes you will need to use a seed in order to get special order or if you need to have different level of shuffling. A possible use case is two decks of cards. You may need to shuffle the decks in similar way - this is possible in Python by using seeds.

In order to verify shuffling and seed you need to have two lists and one seed. This is a basic example showing only how to use seed for one list:

``````import random

SEED = 'abc'

array = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
random.seed(SEED)
random.shuffle(array)

print ( array)
``````

result with seed:

``````['x', 'n', 'y', 'u', 's', 'l', 'i', 'm', 'k', 'c', 'f', 'h', 'r', 'z', 'w', 'b', 'o', 'p', 't', 'e', 'd', 'g', 'v', 'j', 'q', 'a']
``````

result without seed:

``````['u', 'e', 'y', 'b', 'c', 'm', 'g', 't', 'o', 'k', 'v', 'z', 'p', 'w', 'q', 'x', 'n', 'l', 'r', 's', 'a', 'f', 'j', 'd', 'h', 'i']
``````

Another example for shuffle two Python lists preserving the order:

``````import random

for SEED in [1,2,3]:
deck_values = [12, 2, 3, 4]

random.seed(SEED)
random.shuffle(deck_cards)
random.seed(SEED)
random.shuffle(deck_values)

print("List of Cards: ", deck_cards)
print("List of Values: ", deck_values)
``````

In this example you can find how the two lists remain synchronized after several operation of randomizations. If you want to learn more about seeds you can check the resources section about seed.

``````List of Cards:  ['King of Spades', 'Ace of Spades', 'Queen of Spades', 'Jack of Spades']
List of Values:  [4, 12, 3, 2]
List of Values:  [2, 3, 4, 12]
List of Values:  [4, 12, 3, 2]
``````

## Python shuffle list of lists

Another really interesting use case is when you have nested structures with similar data. In this case you can simply iterate the lists and apply the shuffle function.
Shuffling list of lists in python with loop. This will shuffle not only the first level of list elements but also the nested ones. This code works only with two levels of sublists but the same approach can be applied for more levels:

``````import random

mylist = [['a','b','c'],['d','e','f'],['g','h','i']]
random.shuffle(mylist)
for sublist in mylist:
random.shuffle(sublist)
print(mylist)
``````

result:

``````[['h', 'g', 'i'], ['b', 'c', 'a'], ['f', 'e', 'd']]
``````

If you need to use similar way of randomization for the nested list you can combine this code with seeds from the previous sections in order to achieve synchronized shuffling.

## "Reverse" shuffle of list

Sometimes you will need to reverse the shuffling. Depends on the situation it can be possible or you may need to create track of the shuffling - preserving the order of the sequence and later apply it.

Below there are two function which can do:

• shuffle with preserving the order
• reverse the shuffling the previous state
``````import random
import numpy as np

def shuffle_forward(l):
order = list(range(len(l))); random.shuffle(order)
return list(np.array(l)[order]), order

def shuffle_backward(l, order):
l_out =  * len(l)
for i, j in enumerate(order):
l_out[j] = l[i]
return l_out
``````

and here is an example usage of them

``````l = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
random.shuffle(l)
l_shuf, order = shuffle_forward(l)
rev_shuffle  = shuffle_backward(l_shuf, order)

l == rev_shuffle
``````

the result of which is:

True

And the list is:

['f', 'w', 'i', 'y', 'l', 'z', 't', 'v', 'e', 'g', 'x', 'm', 'r', 'a', 'h', 'd', 'b', 'u', 'q', 'n', 'j', 'o', 'p', 's', 'c', 'k']

## Related Articles

better programmer

Python

Python

Selenium

PyCharm

Python

## JIRA how to format code python, SQL, Java

You've successfully subscribed to SoftHints - Python, Data Science and Linux Tutorials
Great! Next, complete checkout for full access to SoftHints - Python, Data Science and Linux Tutorials
Welcome back! You've successfully signed in