In Python, the exclusive or (XOR) operation is represented by the caret symbol ^. The result of XORing two bits is only true when one of the two bits is true and the other is false. This article will teach you how to perform the XOR operation on a list of integers in Python.
Using the reduce() function and the operator module
You can use the reduce() function from the functools module and the xor() function from the operator module to XOR a list of integers. Here’s how it’s done:
from functools import reduce from operator import xor numbers = [5, 3, 7, 2, 9] result = reduce(xor, numbers) print(result)
In the example above, we import the reduce() function and the xor() function. We then define a list of integers named numbers and apply the reduce() function to it, passing the xor() function as the first argument. This code will output 10 as the result of XORing all the integers in the list.
Using a for loop
If you prefer not to use the reduce() function, you can achieve the same result by using a simple for loop:
numbers = [5, 3, 7, 2, 9] result = 0 for number in numbers: result ^= number print(result)
In this example, we initialize a variable named result with the value 0. We then iterate over the list of integers named numbers using a for loop. In each iteration, we XOR the current value of result with the current integer in the list. The final result, 10, is printed at the end.
Conclusion
In this article, we demonstrated two methods to XOR a list of integers in Python: using the reduce() function from the functools module in combination with the xor() function from the operator module, and using a simple for loop. Both methods provide a straightforward way to perform the XOR operation on a list of integers in Python.