0

In a list, is there a way to access the index of the second value using index() method, in the case of the second value is a duplicate of the first value?

num_list = [3,3,6,9]

index1 = num_list.index(num_list[0])
print(index1)  #prints "0" as expected

index2 = num_list.index(num_list[1])
print(index2) #prints "0" while the expected output is "1"
  • https://stackoverflow.com/questions/6294179/how-to-find-all-occurrences-of-an-element-in-a-list may be relevant. – Andrew McClement Mar 05 '22 at 04:06
  • What does "access the index" mean? In your answer, you already have the index, so why go through these contortions? The reason you get "0" instead of "1" is that `.index()` searches for the FIRST element in the list that matches its argument. It does't have any way to know, and doesn't care, where you got that argument from. – CryptoFool Mar 05 '22 at 04:06
  • You may want to check the usage of the `start` parameter of `list.index`: https://docs.python.org/3/tutorial/datastructures.html#more-on-lists – fanfly Mar 05 '22 at 04:08
  • `index` just returns the first occurrence. If you're already finding the first occurrence I guess you could start searching the sublist like `index2 = num_list[index1 + 1:].index(num_list[1])`. This probably isn't recommended, though... – BTables Mar 05 '22 at 04:08
  • This whole thing seems contorted to me. What is it that you really want to do? What is the use case? I expect that for almost any real use case, there would be a simple and obvious solution. I don't see much use in "searching" for something that you already know the location of. I also don't understand why you care if you've got the index of the first 3 or the second one. Again, a use case is needed here to make any sense of this. – CryptoFool Mar 05 '22 at 04:11

0 Answers0