How to Remove Duplicate Tuples from a List in Python?

Estimated read time 2 min read

In Python, you can remove duplicate tuples from a list using several different approaches. One common way to do this is to convert the list to a set, which automatically removes duplicates, and then convert the set back to a list. Here’s an example:

my_list = [(1, 2), (3, 4), (1, 2), (5, 6), (3, 4)]
new_list = list(set(my_list))
print(new_list)  # Output: [(1, 2), (3, 4), (5, 6)]

In this example, the original list my_list contains duplicate tuples (1, 2) and (3, 4). We use the set() function to convert the list to a set, which automatically removes duplicates. Then, we use the list() function to convert the set back to a list, resulting in a new list new_list that contains only unique tuples.

If you need to preserve the original order of the tuples in the list, you can use a for loop and a separate list to keep track of which tuples have already been added to the new list. Here’s an example:

my_list = [(1, 2), (3, 4), (1, 2), (5, 6), (3, 4)]
new_list = []
seen = set()
for t in my_list:
    if t not in seen:
        new_list.append(t)
        seen.add(t)
print(new_list)  # Output: [(1, 2), (3, 4), (5, 6)]

In this example, we initialize an empty list new_list and an empty set seen. We then loop through each tuple t in the original list my_list. If the tuple t has not already been added to the new_list, we append it to the list and add it to the seen set. This ensures that only unique tuples are added to the new list, while preserving the original order.

It’s worth noting that if the tuples in the list contain mutable objects (like lists), the above methods will not work as expected, since sets and tuples are immutable and cannot be modified. In this case, you may need to use a more specialized approach to remove duplicates, such as converting the tuples to a hashable format or using a custom comparison function.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply