Educating yourself does not mean that you were stupid in the first place; it means that you are intelligent enough to know that there is plenty left to 'learn'. -Melanie Joy

Wednesday 13 April 2016

Python - Selecting a random item from a list or tuple or dict

April 13, 2016 Posted by Dinesh ,
Say you have a list with 'n' number of items and you wish to get some random item from that list, How do you do it ?

Python has inbuilt 'random' package to do this.

To get one random item from the list:

>>> import random
>>> items = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> print random.choice(items)
'c'

There’s an equally simple way to select n items from the sequence:

>>> import random
>>> items = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> print random.sample(items, 2)
['e', 'a']