
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Tuple XOR operation in Python
When it is required to perform 'XOR' operations on the elements of one tuple, the 'zip' method and the generator expression can be used.
The zip method takes iterables, aggregates them into a tuple, and returns it as the result.
Generator is a simple way of creating iterators. It automatically implements a class with '__iter__()' and '__next__()' methods and keeps track of the internal states, as well as raises 'StopIteration' exception when no values are present that could be returned.
Below is a demonstration of the same −
Example
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)
Output
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)
Explanation
- Two tuples are defined, and displayed on the console.
- The lists are iterated over, and they are zipped using the 'zip' method.
- The first element is taken and 'XOR'ed with the second element from both the tuples using the '^' operator.
- This is then converted to a tuple.
- This operation is assigned to a variable.
- This variable is the output that is displayed on the console.
- Related Articles
- Program to perform XOR operation in an array using Python
- How to perform bitwise XOR operation on images in OpenCV Python?
- Java Program to perform XOR operation on BigInteger
- How to perform Bitwise XOR operation on two images using Java OpenCV?
- Minimizing array sum by applying XOR operation on all elements of the array in C++
- Flatten tuple of List to tuple in Python
- Database INSERT Operation in Python
- Database READ Operation in Python
- Database Update Operation in Python
- Database DELETE Operation in Python
- Commit & RollBack Operation in Python
- Tuple Division in Python
- Tuple multiplication in Python
- Python set operation.
- What is operation of <> in Python?

Advertisements