3

I have a list of names and using random.choice(), I am able to get a random element from the list. Now I am trying to figure out at what index that given element sits in the list. This is what I have so far:

import random x = ['Jess','Jack','Mary','Sophia','Karen','Addison','Joseph','Eric','Ilona','Jason'] y = random.choice(x) print(y) 
6
  • 1
    x.index(y) will give you the index. Commented Sep 24, 2020 at 6:15
  • does the list contain duplicates? Commented Sep 24, 2020 at 6:15
  • 2
    Yes it will matter. index only returns the first occurrence in the list. Commented Sep 24, 2020 at 6:16
  • 2
    list.index(element, start,end) is the command. So if you dont provide start or end, then it will find the first occurrence. If there are duplicates, it won't find the next one unless you specify the start position Commented Sep 24, 2020 at 6:19
  • 2
    Does this answer your question? How to randomly select an item from a list? See this answer there: stackoverflow.com/a/12373205/7851470 Commented Sep 24, 2020 at 7:22

4 Answers 4

9

You can use list.index():

x.index(y) 

This will return the first index in the list where it finds a match. However, this will not return the correct index if you have duplicates in your list.


A better way to handle this, in the case you have duplicates would be to randomise the index instead of the value. As you will always store the correct index you're referencing and not the first occurance.

y = random.randint(0, len(x)) #3 x[y] #Sophia 
Sign up to request clarification or add additional context in comments.

Comments

6

You can use randrange

import random x = ['Jess','Jack','Mary','Sophia','Karen','Addison','Joseph','Eric','Ilona','Jason'] i = random.randrange(len(x)) print(i, x[i]) 

Example output:

7 Eric

Comments

2

This can be done in 2 ways.

Method 1

  1. Find the length of the list (n) and then choose a random integer from 0-n as K.
  2. 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

Comments

0

You can give y = x.index(random.choice(x)) This will assign the index to y

2 Comments

how your answer is different from @PacketLoss
I guess we both responded at the same time

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.