In python we can sum a list as: sum(list_of_integers).
Now sum is just an operation among two elements with the operator +.
What if I want to sum a list with different operator like or, and, xor etc?
I could do it manually one by one using a for loop, but there must be a better way.
functools.reduce is perfect for this use-case. It takes a function to apply to the accumulated value and the next value, the iterable you want to reduce, and optionally an initialiser.
For example, bitwise-or-ing every value in a list:
import functools
functools.reduce(lambda a, b: a ^ b, [1, 2, 3])
This is equivalent to 1 ^ 2 ^ 3.
The alternative to functools.reduce is to write an explicit for loop:
def xor_reduce(args):
result = 0
for x in args:
result ^= x
return result
xor_reduce([1, 2, 3])
If you are going for the reduce way (not so unreasonable for this, IMO), I would make use of the operator module:
from functools import reduce
from operator import xor
reduce(xor, [1, 2, 3])
The operator module (which is in the standard library and should therefore always be available) also defines all other standard operations as functions, but for or and and a trailing _ is added because they are reserved keywords:
from operator import or_, and_
reduce(or_, [1, 2, 3])
reduce(and_, [1, 2, 3])
Although for these two you could use the built-in functions any and all:
any([1, 2, 3])
all([1, 2, 3])
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