[Python-ideas] list.index() extension

Leif Walsh leif.walsh at gmail.com
Sat Apr 4 23:50:44 CEST 2009


On Sat, Apr 4, 2009 at 5: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),)

print "The first number less than 5 in this list is my_list[%d]=%s" %
((idx, elt) for idx, elt in enumerate(my_list) if elt < 5).next()

Okay, it's sort of ugly and rubyish, but I think it solves your case
sufficiently that we don't need to change index().  If you can come up
with a more pressing reason though, I'm all ears (and fingers,
evidently).

-- 
Cheers,
Leif



More information about the Python-ideas mailing list