How to get an item from a list randomly?

Asked

Viewed 101 times

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?

2 answers

6


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.

  • 1

    Nice add-on. As in PHP there are two ways. Knowing this in Python is also good +1

  • 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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.