I'm new to python. Could someone help me understand why the following function doesn't work? It is supposed to return a new list with the duplicates removed but instead prints [4,6]
.
def remove_duplicates(l):
solution = []
for item in l:
if l.count(item) < 2:
solution.append(item)
else:
l.remove(item)
return solution
print (remove_duplicates([4,5,5,5,4,6]))
I thought it iterates one item at a time in a list. So the first 5 would have a count of 3 and be remove, the second five would have a count of 2 and be removed and the third 5 would have a count of 1 and be appended to the solution list. I can't wrap my head around why the 5s would be completely removed but the 4s would not.