[Python-ideas] all(iterable) should be like all(iterable, key=func)
Steven D'Aprano
steve at pearwood.info
Sun Aug 23 12:39:21 CEST 2015
On Sun, Aug 23, 2015 at 12:01:57PM +0530, shiva prasanth 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
There is no need for the lambda. key=bool will work the same way, and
more efficiently.
> we can also do a lot of things like
> all([2,3,4],key=lamdba a:a) gives false
No, it would return True, since all the items are truthy. lambda a: a is
equivalent to not transforming the items at all, which makes it
equivalent to using bool as the implied key.
You can test that yourself by using:
f = lambda a: a
all(f(a) for a in [2, 3, 4])
There is no need for a key function, since we can get the same result
using either map() or a generator expression:
all(map(keyfunction, iterable))
all(keyfunction(obj) for obj in iterable)
whichever you prefer.
There's no obvious one-liner to check whether an iterable contains only
the same object, but a helper function is easy to write:
def same(iterable):
it = iter(iterable)
try:
first = next(it)
except StopIteration:
return False
return all(obj == first for obj in it)
--
Steve
More information about the Python-ideas
mailing list