Short circuit all() when used with list comprehension

all() already exits early when one of the elements of the iterator is false:

In [1]: def test():
   ...:     yield True
   ...:     print('one')
   ...:     yield False
   ...:     print('two')
   ...:     yield True
   ...:     print('three')
   ...: 

In [2]: all(test())
one
Out[2]: False

However, if you have list comprehension inside of it:

all([False for _ in range(10)]) 

It will evaluate the whole list inside, then go through it again to check for a False value. Would it be a good idea to exit early if the list finds a Falsey value? Most of the time I’m using all() there’s a list comprehension inside it and it would be nice to have this run faster.

Why not use a generator comprehension - all(False for _ in range(10))?

4 Likes

Why not use a generator comprehension - all(False for _ in range(10))?

Oh oops, I didn’t know that was a thing. Thanks!