Python equivalent of sum() using xor()

A one-liner

eval( '^'.join( str(n) for n in nums ) )

nums: an array of int

Explanation

Let's say nums = [7,2,1,8,3,1]

'^'.join( [ str(n) for n in nums ] ) would join nums as follow:

"7^2^1^8^3^1"

eval("7^2^1^8^3^1") would result as 14, which is the XOR sum of nums.


Note that starting Python 3.8, and the introduction of assignment expressions (PEP 572) (:= operator), we can use and update a variable within a list comprehension and thus reduce a list to the xor of its elements:

zxor = 0
[zxor := zxor ^ x for x in [1, 0, 1, 0, 1, 0]]
# zxor = 1

zxor = reduce(lambda a, b: a ^ b, z, 0)

import operator
zxor = reduce(operator.xor, z, 0)

Tags:

Python

Xor

Sum