Wednesday, 13 April 2016

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

If you have a list with n number of items and you wish to print some random item from the list.
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']