[Python-ideas] all(iterable) should be like all(iterable, key=func)

Andrew Barnert abarnert at yahoo.com
Sun Aug 23 09:04:15 CEST 2015


On Aug 22, 2015, at 23:31, shiva prasanth <kesavarapu.siva at gmail.com> wrote:
> 
> functionality of all(iter) is to check all are true by converting it to boolean type
> 
> if it is changed to all(iterable,key=lambda a:bool(a)) it still works and 
> 
> we can also do  a lot of things like 
> all([2,3,4],key=lamdba a:a) gives false
> above checks all are equal or not 

How could it possibly do that? You're calling a key function of one parameter that just returns its argument. That would have the same effect as passing no key at all (except for being a little slower).

And, since a key function gets called once with each element, there's no easy way to turn all into a function that compares every element with all the other elements by adding a key function. I suppose if you really wanted to, you could write something like this:

    def make_cmp():
        sentinel = first = object()
        def cmp(x):
            nonlocal first
            if first is sentinel: first = x
            return x == first
        return cmp
    all([1, 2, 3], key=make_cmp())

... but that would be very silly.

For a much simpler and more readable solution, see the unique_justseen recipe in itertools. If there's a second unique value, the elements weren't all equal.

> all([2,2,2],key=lambda a:a) gives true
> abouve checks all are equal or not
> all([1,2,4,9,key=lambda a:math.sqrt(a)**2==a])

Since math.sqrt returns a float, this will be true for almost all integers. (I'm not sure whether very big ones could fail because of rounding errors.)

So, none of your examples actually work.

And, if you came up with one that did, why wouldn't you just use a generator expression? Which of these is more readable:

    all(x>0 for x in [1, 2, 3])
    all([1, 2, 3], key = lambda x: x>0)



More information about the Python-ideas mailing list