QuestionAccepted answer
Why is any(True for ... if cond) much faster than any(cond for ...)?
no comment
10 Jul 2022, 22:41 UTC
112.9K views1
Two similar ways to check whether a list contains an odd number:
any(x % 2 for x in a)
any(True for x in a if x % 2)
Timing results with a = [0] * 10000000 (five attempts each, times in seconds):
0.60 0.60 0.60 0.61 0.63 any(x % 2 for x in a)
0.36 0.36 0.36 0.37 0.37 any(True for x in a if x % 2)
Why is the second way almost twice as fast?
My testing code:
from timeit import repeat
setup = 'a = [0] * 10000000'
expressions = [
'any(x % 2 for x in a)',
'any(True for x in a if x % 2)',
]
for expression in expressions:
times = sorted(repeat(expression, setup, number=1))
print(*('%.2f ' % t for t in times), expression)
1 answer
Accepted answer · original discussion
Ariadne Paradis
Permalink12 Jul 2022, 22:41 UTC
The first method sends everything to any() whilst the second only sends to any() when there's an odd number, so any() has fewer elements to go through.
1 question comment
Use comments to ask for clarification. Post a solution as an answer.
kojiroPermalink
14 Jul 2022, 22:41 UTC
Another way to look at the filtering approach is
next((True for x in a if x % 2), False), which uses an explicit default to make it clear that the filtering generator doesn't yield any values that are false, even if a only contains even numbers.