[Python-ideas] list.index() extension

Benjamin Peterson benjamin at python.org
Sat Apr 4 23:38:50 CEST 2009

I would like to propose a extra parameter `predicate` to list.index() like this:

def index(self, obj, predicate=operator.eq):
    for idx, item in enumerate(self):
        if predicate(item, obj):
            return idx
    raise IndexError

My main use-case is 2to3 where a node has to locate its self in the parents node
list by identity. Instead of writing out the search manually as is done now, it
would be nice to just write `self.parent.nodes.index(self, operator.is_)`.

I can also imagine this might be useful:

print "The first number less than 5 in this list is %s" % (my_list.index(5,

More information about the Python-ideas mailing list