If I do:
result = reduce(operator.and_, [False] * 1000)
Will it stop after the first result? (since False & anything == False
)
Similarly:
result = reduce(operator.or_, [True] * 1000)
It doesn't. Your alternative in this case is any and all.
result = reduce(operator.and_, [False] * 1000)
result = reduce(operator.or_, [True] * 1000)
can be replaced by
result = all([False] * 1000)
result = any([True] * 1000)
which do short circuit.
The timing results show the difference:
In [1]: import operator
In [2]: timeit result = reduce(operator.and_, [False] * 1000)
10000 loops, best of 3: 113 us per loop
In [3]: timeit result = all([False] * 1000)
100000 loops, best of 3: 5.59 us per loop
In [4]: timeit result = reduce(operator.or_, [True] * 1000)
10000 loops, best of 3: 113 us per loop
In [5]: timeit result = any([True] * 1000)
100000 loops, best of 3: 5.49 us per loop
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With