How to get an item from a list randomly?

5

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?

    
asked by anonymous 09.01.2017 / 19:31

2 answers

6

Answer SOEn , use the random.choice

import random

frutas = ['abacate', 'mamão', 'laranja', 'uva', 'pêra']
print(random.choice(frutas))

Example Online

09.01.2017 / 19:33
5

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 .

    
09.01.2017 / 20:03