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
How to get unique elements in nested tuple in Python
When working with nested tuples, you often need to extract unique elements from all inner tuples. Python provides several approaches to achieve this using sets, loops, and built-in functions.
A set is a built-in Python data type that automatically stores only unique elements. It's perfect for removing duplicates and performing operations like union, intersection, and difference.
Using Nested Loops with Set
This approach manually iterates through each tuple and tracks unique elements ?
my_tuples = [(7, 8, 0), (0, 3, 45), (3, 2, 22), (45, 12, 9)]
print("The list of tuples is:")
print(my_tuples)
unique_elements = []
seen = set()
for inner_tuple in my_tuples:
for element in inner_tuple:
if element not in seen:
seen.add(element)
unique_elements.append(element)
print("The unique elements in the list of tuples are:")
print(unique_elements)
The list of tuples 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]
Using Set with Chain
A more Pythonic approach using itertools.chain to flatten the tuples ?
from itertools import chain
my_tuples = [(7, 8, 0), (0, 3, 45), (3, 2, 22), (45, 12, 9)]
print("The list of tuples is:")
print(my_tuples)
# Flatten and get unique elements
unique_elements = list(set(chain(*my_tuples)))
print("The unique elements in the list of tuples are:")
print(unique_elements)
The list of tuples is: [(7, 8, 0), (0, 3, 45), (3, 2, 22), (45, 12, 9)] The unique elements in the list of tuples are: [0, 2, 3, 7, 8, 9, 12, 22, 45]
Using Set Comprehension
A concise one-liner approach using set comprehension ?
my_tuples = [(7, 8, 0), (0, 3, 45), (3, 2, 22), (45, 12, 9)]
print("The list of tuples is:")
print(my_tuples)
# Set comprehension to get unique elements
unique_elements = list({element for inner_tuple in my_tuples for element in inner_tuple})
print("The unique elements in the list of tuples are:")
print(unique_elements)
The list of tuples is: [(7, 8, 0), (0, 3, 45), (3, 2, 22), (45, 12, 9)] The unique elements in the list of tuples are: [0, 2, 3, 7, 8, 9, 12, 22, 45]
Comparison
| Method | Preserves Order? | Readability | Performance |
|---|---|---|---|
| Nested Loops | Yes | Good | Moderate |
| itertools.chain | No | Good | Fast |
| Set Comprehension | No | Excellent | Fast |
Conclusion
Use nested loops to preserve the order of first occurrence. For better performance and concise code, use set comprehension or itertools.chain when order doesn't matter.
