Ev. Kounis Ev. Kounis - 1 year ago 79
Python Question

Is any() evaluated lazily?

I am writing a script in which i have to test numbers against a number of conditions. If any of the conditions are met i want to return

and i want to do that the fastest way possible.

My first idea was to use
instead of nested
statements or multiple
linking my conditions. Since i would be satisfied if any of the conditions were
i could really benefit from
being lazy and returning True as soon as it could.

Based on the fact that the following print happens instantly and not after 10 (= 0 + 1 + 2 + 3 + 4) seconds i assume it is. Is that the case or am i somehow mistaken?

import time

def some(sec):
return True

print(any(some(x) for x in range(5)))

Answer Source

Yes, any() and all() short-circuit, aborting as soon as the outcome is clear: See 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


Return True if any element of the iterable is true. If the iterable is empty, return False. Equivalent to:

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download