Home >>Python Random Module >Python Random choices() Method

Python Random choices() Method

Python Random choices() Method

Python Random choices() Method in python is used to returns a random selected item of list from the specified sequence a list, a range, a tuple or any other kind of sequence.

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

Parameter Values

Parameter Description
sequence It is Required a sequence like a range ,a list, a tuple of numbers etc.
weights It is Optional. A list of the possibility for each value and their default value is none
cum_weights It is Optional. you can weigh the possibility for each value in a list. Default value is None
k It is Optional. Defining the length of the returned list of an integer.
Here is an example of Python Random choices() Method:

import random
myco = ["Python", "mySql", "Jquery"]
print(random.choices(myco, weights = [5, 2, 3], k = 10))

Output:
['mySql', 'mySql', 'Python', 'Jquery', 'Jquery', 'mySql', 'Jquery', 'Jquery', 'Python', 'Python']
Example 2:

import random
myfruits = ["cherry", "mango", "apple"]
print(random.choices(myfruits, weights = [2, 2, 3], k = 4))

Output:
['cherry', 'mango', 'mango', 'mango']

No Sidebar ads