This can be done in 2 ways.
Method 1
- Find the length of the list (n) and then choose a random integer from 0-n as K.
- Return the element in the list at kth index and the index k
import random x = ['Jess','Jack','Mary','Sophia','Karen','Addison','Joseph','Eric','Ilona','Jason'] k = random.randrange(len(x)) # k is the random index print(x[k], k) # x[k] will be the random element
Method 2
Pick the random element using random.choice and then use list.index to find the index
value= random.choice(x) index= x.index(value)
Note 1: This doesn't work well when duplicate elements are present in the list
Most preferred way would be Method 1
You can also use random.choice to get the index
index = random.choice(range(len(x))) value = x[index]
But this is a bit slow compared to random.randange
indexonly returns the first occurrence in the list.