Computer >> Computer tutorials >  >> Programming >> Python

How to randomly select an item from a list in Python?


Standard library of Python contains random module. This module has various pseudo random generators based on the Mersenne Twister algorithm.

The module contains a choice() method that randomly chooses item from a sequence data type (string, list or tuple)

>>> from random import choice
>>> lst=[1,2,3,4,5]
>>> choice(lst)
4
>>> choice(lst)
5
>>> choice(lst)
3

Another way is to have a random number corresponding to index of list items by using randrange() function. The range for random number is between 0 to len(lst)-1

>>> from random import randrange
>>> lst=[1,2,3,4,5]
>>> index=randrange(len(lst))
>>> lst[index]
4
>>> index=randrange(len(lst))
>>> lst[index]
3