2

As per https://stackoverflow.com/a/17246413/2687324, all() and any() short-circuits. Is the order of evaluation guaranteed?

Using the example from the linked answer:

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

Will the result always be one and False?

Community
  • 1
  • 1
neverendingqs
  • 3,646
  • 3
  • 24
  • 55
  • 2
    It will iterate the iterable in the order of the iterable. If the iterable order of your iterable is stable, so is `all`/`any`. – deceze Jan 06 '17 at 15:04
  • @deceze Quick question: What would an unstable iterable look like? – Quirk Jan 06 '17 at 15:07
  • 1
    An iterable using the `random` function? – Ortomala Lokni Jan 06 '17 at 15:09
  • 3
    As a side note, it is really hard to imagine a reasonable implementation that would short-circuit in an order different to the iteration order. I would even argue that this would break the very definition of *short-circuit evaluation*. – NPE Jan 06 '17 at 15:10

1 Answers1

3

According to the python documentation :

all(iterable)

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 as said in the comments the answer is yes, if the order of your iterable is stable.

wjandrea
  • 23,210
  • 7
  • 49
  • 68
Ortomala Lokni
  • 48,718
  • 17
  • 164
  • 211