0

I have a list like this : [1,12,3,4,4,5,12,15,13,11]

I want to find index of 12 i.e 6. I have tried linear approach but it is not efficient.

item = 12
for i in range(len(mylist)):
    if mylist[i] == item:
        index = i
return index

Any efficient way to get this ?

Kishan Mehta
  • 2,598
  • 5
  • 39
  • 61

3 Answers3

8

Go from right to left:

mylist = [1,12,3,4,4,5,12,15,13,11]
item = 12
for i in range(len(mylist)-1,-1,-1):
    if mylist[i] == item:
        index = i
        print(index)
        break
Dmitriy Fialkovskiy
  • 3,065
  • 8
  • 32
  • 47
3
len(mylist) - list(reversed(mylist)).index(item) -  1

will be enough

vZ10
  • 2,468
  • 2
  • 23
  • 33
2

The last occurrence of an element in a list is same as the first occurrence of that element in the reversed list.

So the index of last occurrence of an element in original list is equal to (length_of_list - index_in_reversed_list - 1).

You can use the list.reverse() method to reverse the list and then find the index of first occurrence of the required element in reversed list by list.index() method.

For example:

>>> mylist = [1,12,3,4,4,5,12,15,13,11]
>>> temp = mylist[:]
>>> temp.reverse()
>>> index = len(temp) - temp.index(12) - 1
>>> print(index)
6
gaurav
  • 136
  • 1
  • 6
  • How is this more "efficient" than the OPs solution? – juanpa.arrivillaga Jun 25 '17 at 06:44
  • @juanpa.arrivillaga thanks for the help. I did not notice that. My mistake. But I corrected it now. – gaurav Jun 25 '17 at 06:50
  • @juanpa.arrivillaga It may not be as much more efficient than the OPs solution, but it provides an elegant way to solve the problem using inbuilt python functions that are anyday faster than your own implementation. – gaurav Jun 25 '17 at 06:52
  • @juanpa.arrivillaga Noted. Thanks again – gaurav Jun 25 '17 at 07:12
  • With most optimize way with respect to time and space complexity: Step-1: Start travelling the original array from last, Step-2: Once you find the given element. Step-3: Return the index = l - i -1; where l = total length of the array, i = index of the element in step-2. – ArunDhwaj IIITH Sep 04 '18 at 17:37