Search code examples
pythonxor

xor of elements of a list/tuple


I have a tuple of '0' and '1', and I want the xor of all its element. For example, if I have ('0', '1', '1', '0'), I want to obtain ((0 xor 1) xor 1) xor 0.

I have the following (working) snippet:

bit = ('0', '1', '0', '1', '0', '1', '0')
out = bit[0]
for i in range(1, len(bit)):
    out = int(out) ^ int(bit[i])
print str(out)

How can I make it in a more pythonic way (using map and a lambda function ?)


Solution

  • print reduce(lambda i, j: int(i) ^ int(j), bit)
    

    reduce(...) reduce(function, sequence[, initial]) -> value

    Apply a function of two arguments cumulatively to the items of a sequence, from left to right, so as to reduce the sequence to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5). If initial is present, it is placed before the items of the sequence in the calculation, and serves as a default when the sequence is empty.