Tex Andersen Tex Andersen - 1 month ago 23
Python Question

Python 3 short-circuit evaluation of list comprehension

When a list comprehension is used as a boolean condition, like so:

if [1 for a in some_list if a.b > 5]:
#some operation


is the list evaluated via short-circuit (until a value is generated within the list), or is the full list comprehension generated prior to the true/false evaluation?

Answer

A list comprehension is always evaluated in full:

>>> def f():
...     print('f')
...     return 1
...
>>>
>>> if [f() for i in range(3)]:
...    print('yes')
...
f
f
f
yes

But you don't have to use a list comprehension:

>>> if any(f() for i in range(3)):
...    print('yes')
...
f
yes

The latter is not exactly the same (if f() returned 0), but just a proof of the idea.

However, applied to the code from question:

if any(a.b > 5 for a in whatever):
    # some operation
Comments