[Python-ideas] list.index() extension

Georg Brandl g.brandl at gmx.net
Sun Apr 5 14:55:28 CEST 2009


Fredrik Johansson schrieb:
> 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.

Or we could finally give in and realize the need for fully generalized list
operations, which were already proposed over 10 years ago.  Sadly, the idea was
never followed through and implemented: <http://tinyurl.com/d8xwee>.

cheers,
Georg

-- 
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