Suppose I have the following list:
frutas = ['abacate', 'mamão', 'laranja', 'uva', 'pêra']
I need to capture one of these elements of list
randomly.
How would I do this in Python?
Suppose I have the following list:
frutas = ['abacate', 'mamão', 'laranja', 'uva', 'pêra']
I need to capture one of these elements of list
randomly.
How would I do this in Python?
Answer SOEn , use the random.choice
import random
frutas = ['abacate', 'mamão', 'laranja', 'uva', 'pêra']
print(random.choice(frutas))
Since it is possible to use random.choice
, on the other hand, if you also want to capture multiple items randomly, you can use random.sample
by passing the list and the number of items to display as a parameter. See:
random.choice ()
import random
print(random.choice(['abacate', 'mamão', 'laranja', 'uva', 'pêra']))
random.sample ()
import random
print(random.sample(['abacate', 'mamão', 'laranja', 'uva', 'pêra'], 3))
Learn more about other methods of module random
in documentation .