+3 votes
2 views
in Python by (4.1k points)
edited by

I have a list:

foo= ['q'' , 'w' , 'e' , 'r' , 't' , 'y']

I want to retrieve an item randomly from this list, How can I do it in python?

2 Answers

0 votes
by (46.1k points)
edited by

It's very simple, just put random.choice()

import random

foo = ['q', 'w', 'e', 'r', 't']
print(random.choice(foo))

If you want to use cryptographically secure random choices then use either random.SystemRandom class or secrets.choice()  :

import random

foo = ['q', 'w', 'e', 'r']
secure_random = random.SystemRandom()
print(secure_random.choice(foo))


 import secrets

foo = ['q', 'w', 'e', 'r', 't']
print(secrets.choice(foo))

0 votes
by (107k points)

If you also need the index, use random.randrange

from random import randrange

random_index = randrange(len(foo))

print(foo[random_index])

You can use the following video tutorials to clear all your doubts:-

Related questions

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...