Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Python's reduce() short circuit?

Tags:

python

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)
like image 589
Brendan Long Avatar asked Aug 25 '10 22:08

Brendan Long


1 Answers

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
like image 175
Muhammad Alkarouri Avatar answered Sep 22 '22 18:09

Muhammad Alkarouri