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

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']

Popular posts from this blog

Reading environment variables in python

ldapmodify failed with error "dn: attribute type undefined"

How to recover a file that was removed using 'rm' command ?