Python random.choices()

Python random.choices()

The choices() method returns multiple random elements from a list with replacement. You can use the weights or cum_weights parameters to weight the likelihood of each outcome. These elements can be a string, a range, a list, a tuple, or any other type of sequence.

Syntax: random.choice(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 that weights the likelihood of each value.

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

Example:

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

Note: The output will be different each time because the system returns a random element.

['geeks', 'geeks', 'geeks', 'for', 'for']

Practical application. Print a random list of 6 items.

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

Note: The output changes each time you use the choice() function.

['apple', 'banana', 'apple', 'apple', 'apple', 'banana']

Leave a Reply

Your email address will not be published. Required fields are marked *