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 – random.choices()
Following is the syntax of choices() method in random module.
f = random.choices(seq, weights=None, cum_weights=None, k=1)
|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.
Example 1 – Choose Random Elements 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.
import random seq = ['apple', 'banana', 'cherry', 'mango'] x = random.choices(seq) print(x)
Now, let us specify k=2 and see the result.
import random seq = ['apple', 'banana', 'cherry', 'mango'] x = random.choices(seq, k = 2) print(x)
Two elements are chosen randomly from the list.
Example 2 – Choose 5 Random Characters from String
In this example, we shall use random.choices() method to choose five characters from given string, randomly.
import random seq = 'abcdefghijklmnopqrstuvwxyz0123456789' x = random.choices(seq, k = 5) print(x)
['s', 'p', '0', 'j', 'w']
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.
- Python – Generate Random String of Specific Length
- Python Program to Generate Random Password
- Python – Generate a Random Number – Positive or Negative
- Python Program to Generate a Random Number of Specific Length
- Python Numpy – Create Array with Random Values
- Python Program to Generate Random Float
- Python Program to Flip a Coin
- Python Random Module Examples
- PyTorch Create Tensor with Random Values and Specific Shape