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
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 performs the symmetric difference operation on sets. It returns elements that are in either set but not in both sets.
Example
Below is a demonstration of finding dissimilar elements between two tuples ?
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)
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))
How It Works
The symmetric difference operation works in three steps:
- Convert both tuples to sets using
set() - Apply the
^operator to find elements present in either set but not in both - Convert the result back to a tuple using
tuple()
Alternative Method Using set.symmetric_difference()
You can also use the symmetric_difference() method for the same result ?
tuple_1 = ((7, 8), (3, 4), (3, 2))
tuple_2 = ((9, 6), (8, 2), (1, 4))
dissimilar = tuple(set(tuple_1).symmetric_difference(set(tuple_2)))
print("Dissimilar elements using symmetric_difference():")
print(dissimilar)
Dissimilar elements using symmetric_difference(): ((3, 4), (9, 6), (1, 4), (8, 2), (3, 2), (7, 8))
Conclusion
The ^ operator provides a concise way to find dissimilar elements between tuples by converting them to sets first. Both ^ and symmetric_difference() methods produce the same result for finding unique elements.
