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
Selected Reading
How to get unique elements in nested tuple in Python
When it is required to get the unique elements in a nested tuple, a nested loop and the 'set' 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.
Below is a demonstration of the same −
Example
my_list_1 = [(7, 8, 0), (0 ,3, 45), (3, 2, 22), (45, 12, 9)]
print ("The list of tuple is : " )
print(my_list_1)
my_result = []
temp = set()
for inner in my_list_1:
for elem in inner:
if not elem in temp:
temp.add(elem)
my_result.append(elem)
print("The unique elements in the list of tuples are : ")
print(my_result)
Output
The list of tuple is : [(7, 8, 0), (0, 3, 45), (3, 2, 22), (45, 12, 9)] The unique elements in the list of tuples are : [7, 8, 0, 3, 45, 2, 22, 12, 9]
Explanation
- A list of tuple is defined, and is displayed on the console.
- An empty list is created, and an empty set is created.
- The list is iterated through, and checked to see if it is present in the list.
- If not, it is added to the list as well as the empty set.
- This result is assigned to a value.
- It is displayed as output on the console.
Advertisements
