Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 686
Monique Bakker Avatar asked May 25 '11 16:05

Monique Bakker


People also ask

How do I randomly select an index in Python?

Using random. randrange() to select random value from a list. random. randrange() method is used to generate a random number in a given range, we can specify the range to be 0 to the length of the list, and get the index, and then the corresponding value.

How do you pull a random item from a list in Python?

Use the random. sample() function when you want to choose multiple random items from a list without repetition or duplicates. There is a difference between choice() and choices() . The choices() was added in Python 3.6 to choose n elements from the list randomly, but this function can repeat items.

How do you select multiple random elements in a list in Python?

You can use random. randint() and random. randrange() to generate the random numbers, but it can repeat the numbers.

How do you select random names from a list without repetition in Python?

Using the choice() method in random module, the choice() method returns a single random item from a list, tuple, or string.


1 Answers

import random l = ['a','b','c','d','e'] i = random.choice(range(len(l))) print i, l[i] 
like image 106
Vader Avatar answered Oct 19 '22 16:10

Vader