Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does all(list) use short circuit evaluation? [duplicate]

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?

like image 681
Sylvester V Lowell Avatar asked Jun 22 '13 01:06

Sylvester V Lowell


2 Answers

Yes, it short-circuits:

>>> def test():
...     yield True
...     print('one')
...     yield False
...     print('two')
...     yield True
...     print('three')
...
>>> all(test())
one
False

From the docs:

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.

like image 102
TerryA Avatar answered Oct 29 '22 10:10

TerryA


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.

like image 40
Óscar López Avatar answered Oct 29 '22 09:10

Óscar López