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
  • 4,006
  • 3
  • 29
  • 57
  • 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
  • 28,235
  • 9
  • 60
  • 81
Ortomala Lokni
  • 56,620
  • 24
  • 188
  • 240