could you please help me find the error in my logic? The function doesn't work well and I can't figure out why. The instructions are: Write a function remove_duplicates that takes in a list and removes elements of the list that are the same. Do not modify the list you take as input! Instead, return a new list. For example: remove_duplicates([1,1,2,2]) should return [1,2].
For [1, 2, 2, 5, 5, 5, 7, 7] I'm getting this output [1, 2, 5, 7], which is good. However, for [4, 9, 9, 4] the output is [9, 9, 4], which is wrong. I can't find out what the problem is. I started learning programming a few weeks ago, so I'm a novice. Thanks!
My code:
def remove_duplicates(l):
nl = list(l)
i = 0
while i <= len(nl)-2:
j = i + 1
while j <= len(nl)-1:
if nl[i] == nl[j]:
nl.remove(nl[j])
else:
j += 1
i += 1
return nl