Showing posts with label sequence. Show all posts
Showing posts with label sequence. Show all posts

Sunday, May 31, 2009

How to choose a random item from a sequence in Python

To choose a random item from a list, use random.choice().

Here is an example.
>>> items = ['Proton', 'Honda', 'Toyota', 'Nissan']
>>> random.choice(items)
'Nissan'
>>> random.choice(items)
'Proton'
>>> random.choice(items)
'Toyota'
Another example of usage is to choose a random file from a directory.
>>> random.choice(os.listdir("C:"))
'ubuntu'
>>> random.choice(os.listdir("C:"))
'tex4ht'