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'
If you are new here, you might want to subscribe to the RSS feed or newsletter.

Enter your email address:

Related

This entry was posted in Python and tagged , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>