[Python-ideas] Provide a 'key' argument for all() and any() builtins
Guido van Rossum
guido at python.org
Mon Jul 23 16:55:32 CEST 2012
On Sun, Jul 22, 2012 at 9:36 PM, Raymond Hettinger
<raymond.hettinger at gmail.com> wrote:
>
> On Jul 22, 2012, at 11:03 PM, Giampaolo RodolĂ wrote:
>
> This would be similar to 'key' argument already available for min(), max()
> and sorted() and would let user decide what must be considered True and what
> not.
>
> There's no need. We already have:
>
> >>> all(predicate(x) for x in iterable)
> >>> any(predicate(x) for x in iterable)
In addition, there's a reason why the key= parameter to sort, sorted,
max and min can't be replaced with a similar idiom: all these return
the *original* object(s) and the key= parameter affects only the
comparison; for example, try max(1,-2,3,-4, key=abs).
Whereas for the current proposal, the value returned by the key would
also determine the outcome -- and then there is no advantage over
using the comprehension. More general, if you can first apply the
transformation (the key function) and then the aggregation function
(min/max/etc.), there's no need to combine the transformation and the
aggregation. But in all the cases that have a key= parameter, this is
not so.
--
--Guido van Rossum (python.org/~guido)
More information about the Python-ideas
mailing list