Random module in Python
Time and again if you are building a small game or if you are trying to pick something randomly in Python, you will have to use Random module.
This write up tries to explore the random module in python.
- As always, to use the random module, import it.
from random import choice, choices, shuffle, sample
- To pick one element out of a list randomly, use choice from random module
>>> what_to_do = ['study', 'play', 'work', 'hobby project', 'sleep', 'read']
>>> choice(what_to_do)
'study'
>>> choice(what_to_do)
'work'
- To pick more than one element at the same time from a list, use choices from random module. The second parameter for choices signifies the number of times an element has to be picked from the list.
Note : In the below code section you can see that, a same element can be picked more than once from a list on using Choices.
>>> choices(what_to_do, k=4)
['work', 'work', 'read', 'study']
>>> choices(what_to_do, k=6)
['work', 'play', 'read', 'sleep', 'read', 'read']
- Now making use of Counters from collection module, we can see how the elements are picked when we decide to choose them from a list for a large number of times. (say over a 1000 times)
>>> from collections import Counter
>>> Counter(choices(what_to_do, k=1000))
Counter({'read': 191, 'work': 182, 'study': 172, 'hobby project': 163, 'sleep': 157, 'play': 135})
Note: Details of using Counter written in a separate article here.
- We can also control the ratios in which the elements are picked from a list. From the above example list, if you love studying and you want it to be picked more often you can set it to higher ratio like the below code.
>>> Counter(choices(what_to_do, [6,5,4,3,2,1], k=1000))
Counter({'study': 291, 'work': 222, 'play': 213, 'hobby project': 137, 'sleep': 93, 'read': 44})
In the above snippet you can note that, "study" is picked over 6 times more than "read". Note : The ratio / weight-age should be provided to each element in the list. Else, a ValueError is raised. In should length of ratio set should be equivalent to the length of list.
- As seen in choices above, as you choose more than one element, there might be a chance of duplication of the element picked. i.e, a same element might be picked twice. To avoid this, you may use sample.
>>> sample(what_to_do, k=4)
['sleep', 'read', 'play', 'work']
- shuffle can be used to shuffle the elements in the list and jumble them up.
>>> what_to_do
['study', 'play', 'work', 'hobby project', 'sleep', 'read']
>>> shuffle(what_to_do)
>>> what_to_do
['read', 'work', 'hobby project', 'study', 'sleep', 'play']
Note that the original list is shuffled above.
Hope this helps.