Python - Choose List of Random Elements from Sequence


Python - random choices()

To choose a list of random elements from given sequence in Python, use choices() method of random package.

The sequence could be a list, tuple, range, string, etc.

The sequence must be non-empty, else Python raises IndexError.

In this tutorial, we shall learn how to choose a list of elements from a given non-empty sequence using random.choices() method.

Syntax of random.choices()

Following is the syntax of choices() method in random module.

f = random.choices(seq, weights=None, cum_weights=None, k=1)

where

ParameterDescription
seq[Mandatory] A non-empty sequence.
weights[Optional] A list with specified probabilities for selection of respective elements from given sequence.
cum_weights[Optional] A list. Functionality is same as that weights list, but the different is that the weights are accumulated.
k[Optional] An integer. Length of returned list. Specifies the number of elements for selection.

choices() method returns a List.

Examples

1. Choose a random element from a List

In this example, we shall use random.choices() method to choose an element randomly from a given list of numbers. The default value for parameter k is 1. Therefore if k is not specified, then only single element is returned in the list.

Python Program

import random

seq = ['apple', 'banana', 'cherry', 'mango']
x = random.choices(seq)
print(x)

Output

['banana']

Now, let us specify k=2 and see the result.

Python Program

import random

seq = ['apple', 'banana', 'cherry', 'mango']
x = random.choices(seq, k = 2)
print(x)

Output

['banana', 'mango']

Two elements are chosen randomly from the list.

2. Choose five random characters from a given string

In this example, we shall use random.choices() method to choose five characters from given string, randomly.

Python Program

import random

seq = 'abcdefghijklmnopqrstuvwxyz0123456789'
x = random.choices(seq, k = 5)
print(x)

Output

['s', 'p', '0', 'j', 'w']

Summary

In this tutorial of Python Examples, we learned how to choose specific number of elements randomly from a given sequence using random.choices() method, with the help of well detailed example programs.