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?
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.
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.
You can use random. randint() and random. randrange() to generate the random numbers, but it can repeat the numbers.
Using the choice() method in random module, the choice() method returns a single random item from a list, tuple, or string.
import random l = ['a','b','c','d','e'] i = random.choice(range(len(l))) print i, l[i]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With