HomeLanguagesrandom.choices() method in Python

random.choices() method in Python

The choices() method returns multiple random elements from the list with replacement. You can weigh the possibility of each result with the weights parameter or the cum_weights parameter. The elements can be a string, a range, a list, a tuple or any other kind of sequence.

Syntax : random.choices(sequence, weights=None, cum_weights=None, k=1)

Parameters :
1. sequence is a mandatory parameter that can be a list, tuple, or string.
2. weights is an optional parameter which is used to weigh the possibility for each value.
3. cum_weights is an optional parameter which is used to weigh the possibility for each value but in this the possibility is accumulated
4. k is an optional parameter that is used to define the length of the returned list.

Note: This method is different from random.choice().

Example:




import random
  
mylist = ["Lazyroar", "for", "python"]
  
print(random.choices(mylist, weights = [10, 1, 1], k = 5))


Note: Every time output will be different as the system returns random elements.
Output:

['Lazyroar', 'Lazyroar', 'Lazyroar', 'for', 'for']

Practical application: Print a random list with 6 items.




import random
  
mylist = ["apple", "banana", "mango"]
  
print(random.choices(mylist, weights = [10, 1, 1], k = 6))


Note: The output changes every time as choices() function is used.
Output:

['apple', 'banana', 'apple', 'apple', 'apple', 'banana']
RELATED ARTICLES

3 COMMENTS

Most Popular

Dominic
32738 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
7124 POSTS0 COMMENTS
Nicole Veronica
12254 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12337 POSTS0 COMMENTS
Shaida Kate Naidoo
7235 POSTS0 COMMENTS
Ted Musemwa
7497 POSTS0 COMMENTS
Thapelo Manthata
7215 POSTS0 COMMENTS
Umr Jansen
7185 POSTS0 COMMENTS