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])