Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
+3 votes
3 views
in Python by (4k 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 (46k 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 (106k 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

Browse Categories

...