
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Dissimilar Elements in Tuples in Python
When it is required to find dissimilar elements in tuples, the 'set' operator and the '^' operator can be used.
Python comes with a datatype known as 'set'. This 'set' contains elements that are unique only.
The set is useful in performing operations such as intersection, difference, union and symmetric difference.
The '^' operator is a bitwise operator that performs the 'XOR' operation. It sets every bit to 1 if only one of the two bits is 1.
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, 4)) print ("The first tuple is : " ) print(my_tuple_1) print ("The second tuple is : " ) print(my_tuple_2) my_result = tuple(set(my_tuple_1) ^ set(my_tuple_2)) print("The dissimilar elements in the tuples are : ") print(my_result)
Output
The first tuple is : ((7, 8), (3, 4), (3, 2)) The second tuple is : ((9, 6), (8, 2), (1, 4)) The dissimilar elements in the tuples are : ((3, 4), (9, 6), (1, 4), (8, 2), (3, 2), (7, 8))
Explanation
- Two nested tuples/tuple of tuples are defined and are displayed on the console.
- The '^' operator is used to find the elements that are not similar to one other.
- This result is assigned to a variable.
- It is displayed as output on the console.
Advertisements