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>Yes, and here is an experiment that shows it even more definitively than your timing experiment:</p>

<pre><code>import random

def some(x):
    print(x, end = ', ')
    return random.random() &lt; 0.25

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

<p>typical run:</p>

<pre><code>0, 1, 2, True
0, 1, True
0, True
0, 1, 2, 3, True
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, False
</code></pre>

python