Python Forum
Deleting duplicates in tuples
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Deleting duplicates in tuples
#1
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)  
     
Reply
#2
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?
Reply
#3
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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  remove partial duplicates from csv ledgreve 0 788 Dec-12-2022, 04:21 PM
Last Post: ledgreve
  Problem : Count the number of Duplicates NeedHelpPython 3 4,380 Dec-16-2021, 06:53 AM
Last Post: Gribouillis
  Removal of duplicates teebee891 1 1,797 Feb-01-2021, 12:06 PM
Last Post: jefsummers
  Displaying duplicates in dictionary lokesh 2 1,997 Oct-15-2020, 08:07 AM
Last Post: DeaD_EyE
  how do i pass duplicates in my range iterator? pseudo 3 2,360 Dec-18-2019, 03:01 PM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020