any() and all() Was: Pre-PEP: Dictionary accumulator methods

Raymond Hettinger vze4rx4y at verizon.net
Sat Mar 19 04:31:17 EST 2005


[Roose]
> Actually I was just looking at Python 2.5 docs since you mentioned this.
>
> http://www.python.org/dev/doc/devel/whatsnew/node3.html
>
> It says min() and max() will gain a key function parameter, and sort()
> gained one in Python 2.4 (news to me).

It also appears in itertools.groupby() and, for Py2.5, in heapq.nsmallest() and
heapq.nlargest().


> And they do indeed default to the identity in all 3 cases, so this seems
> very inconsistent.  If one of them has it, and sort gained the argument even
> in Python 2.4 with generator expressions, then they all should have it.
>
> >     any(x >= 42 for x in data)
>
> Not to belabor the point, but in the example on that page, max(L, key=len)
> could be written max(len(x) for x in L).

Think about it.  A key= function is quite a different thing.  It provides a
*temporary* comparison key while retaining the original value.  IOW, your
re-write is incorrect:

>>> L = ['the', 'quick', 'brownish', 'toad']
>>> max(L, key=len)
'brownish'
>>> max(len(x) for x in L)
8


Remain calm.  Keep the faith.  Guido's design works fine.

No important use cases were left unserved by any() and all().



Raymond Hettinger





More information about the Python-list mailing list