Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I randomly select an item from a list?

Assume I have the following list:

foo = ['a', 'b', 'c', 'd', 'e'] 

What is the simplest way to retrieve an item at random from this list?

like image 320
Ray Avatar asked Nov 20 '08 18:11

Ray


People also ask

How do you randomly select an item in a list Python?

In Python, you can randomly sample elements from a list with choice() , sample() , and choices() of the random module. These functions can also be applied to a string and tuple. choice() returns one random element, and sample() and choices() return a list of multiple random elements.

How do I randomly select multiple items from a list in Python?

You can use random. randint() and random. randrange() to generate the random numbers, but it can repeat the numbers.


1 Answers

Use random.choice():

import random  foo = ['a', 'b', 'c', 'd', 'e'] print(random.choice(foo)) 

For cryptographically secure random choices (e.g., for generating a passphrase from a wordlist), use secrets.choice():

import secrets  foo = ['battery', 'correct', 'horse', 'staple'] print(secrets.choice(foo)) 

secrets is new in Python 3.6. On older versions of Python you can use the random.SystemRandom class:

import random  secure_random = random.SystemRandom() print(secure_random.choice(foo)) 
like image 87
Pēteris Caune Avatar answered Oct 13 '22 07:10

Pēteris Caune