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

By | April 28, 2020

In this tutorial, we will introduce random.sample() function, which will capture some random elements from a python sequence. It is very helpful to generate a randomized sequence.

Understand Python random.sample()

What is random.sample()

random.sample() is defined as:

random.sample(sequence, k)

It returns k length randomized sequence from sequence.

We will use some examples to illustrate you how to use this function.

Randomize a python list

Here is an example:

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

lx = random.sample(list, len(list))
print(lx)

The result is:

['tutorialexample.com', 'tutorial', 'python list', 'python']

From the result, we can find random.sample() function will return a new object, which will not change the value of python list list. It is different to random.shuffle().

If you only get 2 length, you can do like this:

lx = random.sample(list, 2)
print(lx)

Then you will get:

['python list', 'python']

Randomize a python tuple

Python tuple is an immutable sequence, to shuffle it, we can do like this:

x = (1, 2, 3, 4)
xs = random.sample(x, len(x))
print(xs)

The randomized pytho tuple is:

[1, 3, 4, 2]

Leave a Reply