Understand Python random.shuffle(): Randomize a Sequence

By | April 28, 2020

In python, we can use random.shuffle() to randomize all elements in a sequence. However, to use this function correctly, there are some notices you should concern. In this tutorial, we will discuss this function.

What is random.shuffle()

random.shuffle() function is in random package. It is defined as:

random.shuffle(x[, random])

It can randomize a mutable sequence.

Shuffle a python list

Python list is a mutable type. We can use this function to randomize all elements in a list.

Here is an example.

import random
l = ['tutorial','python', 'tutorialexample.com', 'python list']

lx = random.shuffle(l)
print(type(lx))
print(l)

Run this result, we can get a sequence like:

<class 'NoneType'>
['tutorialexample.com', 'python', 'python list', 'tutorial']

From the result, we can find:

1.random.shuffle() will renturn a NoneType

2.This function will change the value of a sequence. As example above, the value of python list l is changed.

Can random.shuffle() can randomize an immutable sequence?

The answer is not.

Here is an example:

x = (1, 2, 3, 4)
random.shuffle(x)
print(x)

Here x is a python tuple, which is an immutable sequence.

Run this example code, you will get this result.

TypeError: ‘tuple’ object does not support item assignment

It means we can not use random.shuffle() to shuffle an immutable sequence in python.

To shuffle an immutable sequence, you can use random.sample() function. Here is a tutorial.

Understand Python random.sample(): Return a Random Sample Sequence

Leave a Reply

Your email address will not be published. Required fields are marked *