python: how to know the index when you randomly select an element from a sequence with random.choice(seq)

Monique Bakker picture Monique Bakker · May 25, 2011 · Viewed 20.8k times · Source

I know very well how to select a random item from a list with random.choice(seq) but how do I know the index of that element?

Answer

Vader picture Vader · May 25, 2011
import random
l = ['a','b','c','d','e']
i = random.choice(range(len(l)))
print i, l[i]