Last Updated : 12 Jul, 2025
The choices() method returns multiple random elements from the list with replacement. Unlike random.choice(), which selects a single item, random.choices() allows us to select multiple items making it particularly useful for tasks like sampling from a population or generating random data.
Example:
Python
import random
a = ["geeks", "for", "python"]
print(random.choices(a, weights = [10, 1, 1], k = 5))
['geeks', 'geeks', 'geeks', 'geeks', 'geeks']
Explanation:
Note: Every time output will be different as the system returns random elements.
Let's take a closer look at random.choices() method:
Syntax of random.choices()random.choices(population, weights=None, cum_weights=None, k=1)
Parameters
- population: The sequence (list, tuple, string, etc.) from which random selections are made.
- weights: (Optional) A sequence of weights corresponding to each element in the population. Elements with higher weights are more likely to be selected.
- cum_weights: (Optional) A sequence of cumulative weights. If provided, this is an alternative to using the weights parameter.
- k: The number of items to return. By default, it returns one item.
import random
# Example 1: Simple Random Selection
a = ['apple', 'banana', 'cherry', 'date']
res = random.choices(a, k=3)
print(res)
# Example 2: Random Selection with Weights
w = [10, 20, 5, 1]
res = random.choices(a, weights=w, k=3)
print(res)
# Example 3: Random Selection with Cumulative Weights
cw = [10, 30, 35, 36] # Cumulative sum of weights
res = random.choices(a, cum_weights=cw, k=3)
print(res)
# Example 4: Selecting Random Characters from a String
ch = "abcdefghijklmnopqrstuvwxyz"
res = random.choices(ch, k=5)
print(res)
['cherry', 'apple', 'apple'] ['cherry', 'banana', 'banana'] ['cherry', 'cherry', 'banana'] ['c', 'd', 'm', 'z', 's']
Explanation:
It allows for sampling with replacement, meaning the same item can be selected multiple times. Common practical applications include:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4