.choices()
Published Nov 22, 2024
Contribute to Docs
The .choices()
function in Python returns a list of randomly selected elements from a given sequence, allowing weighted probabilities and repetition.
Syntax
random.choices(sequence, weights=None, *, cum_weights=None, k=1)
sequence
: The sequence (list, tuple, etc.) from which random elements are chosen.weights
(Optional): A sequence of relative weights corresponding to each element insequence
, determining the likelihood of selection.cum_weights
(Optional): A sequence of cumulative weights. It is an alternative toweights
and cannot be used simultaneously.k
(Optional): The number of elements to select. Defaults to1
.
Note: Either
weights
orcum_weights
can be used, but not both.
Example 1
The following example uses .choices()
to randomly select 10 fruits from a predefined list, where the likelihood of each fruit being chosen is determined by its respective weights:
import random# Define the population of itemsfruits = ['apple', 'banana', 'cherry', 'date']# Define weights for each fruit (higher weight means higher likelihood of selection)weights = [5, 20, 50, 25] # 'cherry' is most likely to be picked, followed by 'date', 'banana', and 'apple'# Number of random selections to makenum_picks = 10# Randomly select items based on the weightsselected_fruits = random.choices(fruits, weights=weights, k=num_picks)# Output the selected itemsprint("Randomly selected fruits:", selected_fruits)
The above code produces the following output:
Randomly selected fruits: ['cherry', 'date', 'apple', 'cherry', 'cherry', 'cherry', 'cherry', 'cherry', 'date', 'date']
The output changes with each execution as random.choices()
generates random selections influenced by the weights.
Codebyte Example
This example uses .choices()
to randomly draw 5 cards from a deck, assigning higher weights to face cards to make them more likely to be selected:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours