I was answering this question, and used yield
for the solution, and another answer used any
.
Prompted by OP, I timed the two, and found yield
significantly outperforms any
.
I tested for more general case:
Find if any number exists that is greater than 460 in natural numbers upto 1000.
Here's the performance:
setup = """
z = list(range(1000))
def check(lst):
for l in lst:
if l>460:
yield True
yield False"""
timeit.timeit('next(check(z))',setup=setup)
# 9.688747814000635
timeit.timeit('any(_z>460 for _z in z)',setup='z = list(range(1000))')
# 21.593566988999555
My question is, any
uses short-circuit evaluation, and breaks as soon as a match is found, and yield
halts when it finds the first match, then why is this massive difference between yield
and any
?
NOTE: Python version: 3.7.3, OS: Windows 10 64-bit (found similar results on CentOS, python 3.6)