I wish to use the Python all() function to help me compute something, but this something could take substantially longer if the all() does not evaluate as soon as it hits a False. I'm thinking it probably is short-circuit evaluated, but I just wanted to make sure. Also, is there a way to tell in Python how the function gets evaluated?
Yes, it short-circuits:
>>> def test():
... yield True
... print('one')
... yield False
... print('two')
... yield True
... print('three')
...
>>> all(test())
one
False
Return True if all elements of the iterable are true (or if the iterable is empty). Equivalent to:
def all(iterable):
for element in iterable:
if not element:
return False
return True
So when it returns False, then the function immediately breaks.
Yes, all does use short-circuit evaluation. For example:
all(1.0/x < 0.5 for x in [4, 8, 1, 0])
=> False
The above stops when x reaches 1 in the list, when the condition becomes false. If all weren't short-circuiting, we'd get a division by zero when x reached 0.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With