0

I am trying to complete a coding challenge where I have to remove duplicates of tuples in a list.

Right now, the .remove() method seems to be removing both my (1,1) tuples and not the (2,2) tuple.

def remove_duplicates(lis):
    for i in range(len(lis)):
        print(f"We are at i = {i}")
        for j in range(i + 1, len(lis)):
            
            print(f"j={j}")
            print(f"This is lis[i] {lis[i]}")
            print(f"This is lis[j] {lis[j]}")

            if lis[i] == lis[j]:
                to_remove = lis[j]
                lis.reverse() # reversal is done to remove the last matching element
                lis.remove(lis[j]) 
                lis.reverse() 
    print(lis)
    return lis

lis = [(1,1), (2,2), (3,3), (2,2), (1,1)] 
remove_duplicates(lis) # should return [(1,1), (2,2), (3,3)]

OUTPUT

enter image description here

Mashie
  • 41
  • 3
  • Life is much simpler if you build a new list, then replace the elements of `lis` with the contents of the new list if necessary. The overhead should be comparable to (or less than!) the repeated resizing of the original list when you remove an item. – chepner Apr 09 '22 at 16:10
  • You are also going to have problems because you are removing items from a list while iterating over it. Once you have removed an element, the list is shorter and the index `i` or `j` may become out of bounds. See the linked duplicate question. – kaya3 Apr 09 '22 at 16:13

1 Answers1

0

To remove duplicates, you can transform your list to a set and back to list:

def remove_duplicates(lis):
    return list(set(lis))
juhat
  • 342
  • 2
  • 10