Python Forum
Deleting duplicates in tuples - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Deleting duplicates in tuples (/thread-23179.html)



Deleting duplicates in tuples - Den - Dec-14-2019

I have a list of tuples, and I am trying to delete some tuples of the list based on their first element: if the first element is the same first element of the next tuple, then the second tuple, which contains that same first element, should be deleted. I tried doing it through an iterative loop, but it doesn't completely work. Some duplicates are still left in the list.
 for tuple in list:
         index_of_the_first_tuple=list.index(tuple)
         if tuple[0] in list[index_of_the_first_tuple+1]:
             list.pop(index_of_the_first_tuple+1)  
     



RE: Deleting duplicates in tuples - Gribouillis - Dec-14-2019

Den Wrote:then the second tuple, which contains that same first element, should be deleted.
What about the third tuple containing the same first element. Does it need to be deleted too?


RE: Deleting duplicates in tuples - ichabod801 - Dec-14-2019

You shouldn't use the names of Python built-ins (like tuple and list) for you variable names, because then you lose access to the built-ins. You should also avoid modifying a list that you are iterating over. That's probably why your program is failing. You should build a new list without the items you want to remove:

new_data = data[:1]
for item in data[1:]:
    if item[0] != new_data[-1][0]:
        new_data.append(item)
data = new_data
Note that this will delete the third and succeeding duplicates taht Gribouillis mentioned. Also, if the list is not sorted, it will not remove all of the duplicates.