[Python-ideas] list.index() extension

Georg Brandl g.brandl at gmx.net
Sun Apr 5 12:00:29 CEST 2009

Benjamin Peterson schrieb:
> 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),)

-1.  The list API is the prototype of all mutable sequence APIs (as now fixed
in the corresponding abc class).  It is meant to be simple and easy to
understand.  Adding features to it should be done very carefully, and this seems
like a random one of ten similar features that could be added.

There's nothing wrong with a three-line helper function, or a list subclass
that has the additional method you're looking for.


Thus spake the Lord: Thou shalt indent with four spaces. No more, no less.
Four shall be the number of spaces thou shalt indent, and the number of thy
indenting shall be four. Eight shalt thou not indent, nor either indent thou
two, excepting that thou then proceed to four. Tabs are right out.

More information about the Python-ideas mailing list