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

1
  • 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, 2015 at 20:29

1 Answer 1

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