xor of elements of a list/tuple

In Python 3 you can use:

>>> from functools import reduce
>>> from operator import xor
>>> bits = ('0', '1', '0', '1', '0', '1', '0')
>>> reduce(xor, map(int, bits))
1

Or if you want a running XOR:

>>> from itertools import accumulate
>>> from operator import xor
>>> bits = ('0', '1', '0', '1', '0', '1', '0')
>>> list(accumulate(map(int, bits), xor))
[0, 1, 1, 0, 0, 1, 1]

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.


Kidly take a look at this version is if you are looking for a solution without using reduce or lambda function

A = [1,1,2,3,4,4,5,5]
x = 0
for i in A:
    x ^= i

print(x)
output : 3

As has been mentioned, reduce works well. If you read about reduce, you will come across the concept of a fold which is a higher order function (like map).

In some languages you can fold left or right. Interestingly in your case, you would get the same result if you started from the left or the right as xor is commutative and associative.

Tags:

Python

Xor