Python – Filter unique valued tuples

When it is required to filter unique valued tuples from a list of tuples, the set() method can be used to remove duplicates. However, since the example doesn't contain actual duplicates, let's explore different scenarios and approaches.

Basic Approach Using set()

The most straightforward way to filter unique tuples is converting the list to a set and back to a list ?

my_list = [(42, 51), (46, 71), (14, 25), (26, 91), (56, 0), (11, 1), (99, 102)]
print("The list of tuple is :")
print(my_list)

my_result = list(set(my_list))
print("The result after removing duplicates is :")
print(my_result)
The list of tuple is :
[(42, 51), (46, 71), (14, 25), (26, 91), (56, 0), (11, 1), (99, 102)]
The result after removing duplicates is :
[(42, 51), (46, 71), (14, 25), (26, 91), (56, 0), (11, 1), (99, 102)]

Example with Actual Duplicates

Here's a more realistic example that demonstrates filtering duplicates ?

data = [(1, 2), (3, 4), (1, 2), (5, 6), (3, 4), (7, 8)]
print("Original list with duplicates:")
print(data)

unique_tuples = list(set(data))
print("After filtering unique tuples:")
print(unique_tuples)
Original list with duplicates:
[(1, 2), (3, 4), (1, 2), (5, 6), (3, 4), (7, 8)]
After filtering unique tuples:
[(1, 2), (3, 4), (5, 6), (7, 8)]

Preserving Order with dict.fromkeys()

To maintain the original order while removing duplicates, use dict.fromkeys() ?

data = [(1, 2), (3, 4), (1, 2), (5, 6), (3, 4), (7, 8)]
print("Original list:")
print(data)

unique_ordered = list(dict.fromkeys(data))
print("Unique tuples preserving order:")
print(unique_ordered)
Original list:
[(1, 2), (3, 4), (1, 2), (5, 6), (3, 4), (7, 8)]
Unique tuples preserving order:
[(1, 2), (3, 4), (5, 6), (7, 8)]

Comparison

Method Preserves Order? Performance Best For
set() No Fast When order doesn't matter
dict.fromkeys() Yes Fast When order preservation is needed

Conclusion

Use set() for quick duplicate removal when order doesn't matter. For order preservation, dict.fromkeys() is the most efficient approach in modern Python versions.

Updated on: 2026-03-26T01:32:46+05:30

295 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements