Is any() evaluated lazily?
<p>I am writing a script in which i have to test numbers against a number of conditions. If <strong>any</strong> of the conditions are met i want to return <code>True</code> and i want to do that the fastest way possible.</p>

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

<p>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?</p>

<pre><code>import time

def some(sec):
    time.sleep(sec)
    return True

print(any(some(x) for x in range(5)))
</code></pre>

<p>As Tim correctly mentioned, <code>any</code> and <code>all</code> do short-circuit, but in your code, what makes it <em>lazy</em> is the use of <a href="http://stackoverflow.com/questions/47789/generator-expressions-vs-list-comprehension">generators</a>. For example, the following code would not be lazy:</p>

<pre><code>print(any([slow_operation(x) for x in big_list]))
</code></pre>

<p>The list would be fully constructed and calculated, and only then passed as an argument to <code>any</code>.</p>

<p>Generators, on the other hand, are iterables that calculate each item on demand. They can be <a href="https://www.python.org/dev/peps/pep-0289/" rel="nofollow">expressions</a>, <a href="https://www.python.org/dev/peps/pep-0255/" rel="nofollow">functions</a>, or sometimes manually implemented as lazy <a href="https://docs.python.org/3/tutorial/classes.html#iterators" rel="nofollow">iterators</a>.</p>

python