ActiveState Code

Recipe 576426: get index of element in list using identity


my_list.index(element) returns the index of the element using common comparision (as in == or __eq__() or __cmp__()). If you need to find an element on the list using identity comparing (is) then this function can do it for you

Python
1
2
def index_id(a_list, elem):
    return (index for index, item in enumerate(a_list) if item is elem).next()

Discussion

This approach iterates on the list until it finds the first element that matches and returns it without searching the rest of the list.

Sign in to comment