tags:

views:

147

answers:

2

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)
+12  A: 

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
Muhammad Alkarouri
You're right. `any()` and `all()` seem to be exactly what I need (and probably clearer too). How did you do that timing?
Brendan Long
I am using `ipython` and its `timeit` command. But Python has a timeit module. So you can do `python -mtimeit "result = any([True] * 10)"` from the command line for timing.
Muhammad Alkarouri
+1  A: 

Not only does reduce() not short-circuit, it cannot possibly short-circuit over all the items being reduced, because it only considers the items two at a time. Additionally, it has no idea of the conditions under which the function being used short-circuits. (It would be sorta nifty if functions could have a property that indicates the value at which they begin to short-circuit, which reduce() could then recognize and use, but they don't.)

kindall