Just getting back to this, I was curious how well any would perform compared with a for..if, and for..if won pants down. Although I was a little surprised at how slow both were
from time import time
a = [0]
a.extend([0]*10000000)
a.append(1)
print 'Using any:'
for i in range(10):
t = time()
p = any([b == 1 for b in a])
print time()-t
print ''
print 'Using for..if:'
for i in range(10):
t = time()
for c in a:
if c == 1:
break
print time()-t
Try dropping the square brackets. any can take a generator expression directly. With the square brackets, you're collecting to a list, then evaluating any; no chance to short-circuit.
Without square brackets they're pretty close, though for still wins:
Ah, I must have missed that Victor didn’t include the brackets. I admit i’ve never bothered to read up on generators despite seeing them mentioned, but I will! Cheers
Using a generator is far quicker than using a list, but for…if still appears to win?
Both should be using an iterator object created from the initial list via the for loop's syntactic sugar.
The manual entry for any essentially contains the snippet of code in the second case: https://docs.python.org/2/library/functions.html#any
Yeah, but in the generator you’re not. [b==1 for b in a] would generate a list like [1,1,1,....,1] so any would short circuit on the first element not the last.
For instance:
from time import time
a = [0]
a.extend([0] * 10000000)
a.append(1)
print 'Using any(b == a):'
for i in range(3):
t = time()
p = any(b == 1 for b in a)
print time() - t
print ''
print 'Using for..if:'
for i in range(3):
t = time()
for c in iter(b == a for b in a):
if c:
break
print time() - t
results in:
Using any(b == 1):
1.50999999046
1.54399991035
1.47600007057
Using for..if:
1.90899991989
1.9430000782
1.87400007248
>>>
but:
from time import time
a = [0]
a.extend([0] * 10000000)
a.append(1)
print 'Using any(b == a):'
for i in range(3):
t = time()
p = any(b == a for b in a)
print time() - t
print ''
print 'Using for..if:'
for i in range(3):
t = time()
for c in iter(b == a for b in a):
if c:
break
print time() - t
results in:
Using any(b == a):
1.09200000763
1.04399991035
0.960000038147
Using for..if:
1.99799990654
1.97000002861
1.95200014114
>>>