0

If I'm working with a list containing duplicates and I want to know the index of a given occurrence of an element but I don't know how many occurrences of that element are in the list, how do I avoid calling the wrong occurrence?

Thanks

Paco Poler
  • 201
  • 1
  • 3
  • 12
  • you could call index twice using the first result as the starting point of the second. Is `somelist.index(someval, somelist.index(someval)+1)` close enough? – tdelaney Nov 27 '15 at 20:29

1 Answers1

0

I don't know that a single builtin does this thing alone, but you could fairly easily write it, for instance:

def index_second_occurence(alist, athing): 
    if alist.count(athing) > 1:
        first = alist.index(athing)
        second = alist[first + 1::].index(athing)
        return second + first + 1
    else:
        return - 1
GL2014
  • 6,016
  • 4
  • 15
  • 22