[Python-ideas] list.index() extension

Fredrik Johansson fredrik.johansson at gmail.com
Sun Apr 5 12:31:30 CEST 2009

On Sat, Apr 4, 2009 at 11:38 PM, Benjamin Peterson <benjamin at python.org> wrote:
> 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,
> operator.lt),)

It would be more natural to pass a single predicate function than an argument
and a binary operator, as this is more general. I wouldn't mind predicate-based
index and count somewhere in the standard library.

Meanwhile, here is yet another solution (although not so efficient).

class match:
    def __init__(self, predicate):
        self.__eq__ = predicate

range(10,-10,-1).index(match(lambda x: x < 5))
range(10,-10,-1).count(match(lambda x: x < 5))


More information about the Python-ideas mailing list