5
Suppose I have the following list:
frutas = ['abacate', 'mamão', 'laranja', 'uva', 'pêra']
I need to capture one of these elements from list
randomly.
How would I do it in Python?
5
Suppose I have the following list:
frutas = ['abacate', 'mamão', 'laranja', 'uva', 'pêra']
I need to capture one of these elements from list
randomly.
How would I do it in Python?
6
Answer Soen, use the Random.Choice
import random
frutas = ['abacate', 'mamão', 'laranja', 'uva', 'pêra']
print(random.choice(frutas))
Reference:
5
Whereas it is possible to use the random.choice
, on the other hand, if you also want to capture several items randomly, you can use random.sample
passing as parameter the list and the number of items to display. See:
Random.Choice()
import random
print(random.choice(['abacate', 'mamão', 'laranja', 'uva', 'pêra']))
Random.()
import random
print(random.sample(['abacate', 'mamão', 'laranja', 'uva', 'pêra'], 3))
Learn more about other module methods random
in the documentation.
Browser other questions tagged python list random
You are not signed in. Login or sign up in order to post.
Nice add-on. As in PHP there are two ways. Knowing this in Python is also good +1
– Wallace Maxters
Very good, the output is thus choosing 2 using the Random.sample:
['pêra', 'uva']
Can you format this output without having to assign it to another variable? To have an output like this for example:pêra, uva
.– Laércio Lopes