[Python-ideas] list.index() extension

Carl Johnson cmjohnson.mailinglist at gmail.com
Mon Apr 6 01:06:11 CEST 2009


Fredrik Johansson wrote:

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

I find that sort of elegant, but it won't work with new style classes
as written. It needs to have the __eq__ on the class instead of on the
instance:

>>> class match(object):
...     def __init__(self, predicate):
...         self.predicate = predicate
...     def __eq__(self, item):
...         return self.predicate(item)
...
>>> range(10,-10,-1).index(match(lambda x: x < 5))
6
>>> range(10,-10,-1).count(match(lambda x: x < 5))
14

Also, the examples given before using .next() look slightly less bad
when written with the 2.6/3.0 next function:

index = next(i for i, v in enumerate(range(-10, 10)) if v is 5)

-- Carl Johnson



More information about the Python-ideas mailing list