Search code examples
pythonsumxor

Python equivalent of sum() using xor()


I like the Python sum function :

>>> z = [1] * 11
>>> zsum = sum(z)
>>> zsum == 11
True

I want the same functionality with using xor (^) not add (+). I want to use map. But I can not work out how to do this. Any hints?

I am not satisfied with this :

def xor(l):
    r = 0
    for v in l: r ^= v
    return v

I want a 1 liner using map. Hints?


Solution

  • zxor = reduce(lambda a, b: a ^ b, z, 0)
    
    import operator
    zxor = reduce(operator.xor, z, 0)