Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Tuple XOR operation in Python
When it is required to perform XOR operations on corresponding elements of two tuples, the zip() method and generator expression can be used together.
The zip() method takes iterables, pairs corresponding elements together, and returns an iterator of tuples. The XOR operator (^) performs bitwise XOR operation between integers.
A generator expression provides a memory-efficient way to create iterators. It automatically implements __iter__() and __next__() methods and raises StopIteration when no values remain.
Example
Here's how to perform XOR operation on corresponding elements of two tuples ?
my_tuple_1 = (7, 8, 3, 4, 3, 2)
my_tuple_2 = (9, 6, 8, 2, 1, 0)
print("The first tuple is:")
print(my_tuple_1)
print("The second tuple is:")
print(my_tuple_2)
my_result = tuple(elem_1 ^ elem_2 for elem_1, elem_2 in zip(my_tuple_1, my_tuple_2))
print("The XORed tuple value is:")
print(my_result)
The first tuple is: (7, 8, 3, 4, 3, 2) The second tuple is: (9, 6, 8, 2, 1, 0) The XORed tuple value is: (14, 14, 11, 6, 2, 2)
How XOR Works
Let's understand how XOR operations work on the first pair ?
# XOR of 7 and 9
print("7 in binary:", bin(7))
print("9 in binary:", bin(9))
print("7 ^ 9 =", 7 ^ 9)
print("Result in binary:", bin(7 ^ 9))
7 in binary: 0b111 9 in binary: 0b1001 7 ^ 9 = 14 Result in binary: 0b1110
Using Different Approaches
Using map() Function
import operator
tuple1 = (7, 8, 3, 4, 3, 2)
tuple2 = (9, 6, 8, 2, 1, 0)
result = tuple(map(operator.xor, tuple1, tuple2))
print("XOR result using map():", result)
XOR result using map(): (14, 14, 11, 6, 2, 2)
Using List Comprehension
tuple1 = (7, 8, 3, 4, 3, 2)
tuple2 = (9, 6, 8, 2, 1, 0)
result = tuple([a ^ b for a, b in zip(tuple1, tuple2)])
print("XOR result using list comprehension:", result)
XOR result using list comprehension: (14, 14, 11, 6, 2, 2)
Key Points
- The
^operator performs bitwise XOR between integers -
zip()pairs corresponding elements from both tuples - Generator expressions are memory-efficient for creating new tuples
- Both tuples must have the same length for element-wise operations
Conclusion
Use zip() with generator expressions to perform XOR operations on tuple elements. The map() function with operator.xor provides an alternative approach for the same result.
