How can I use “not in” to remove duplicates from a list?

Code:

def remove_duplicates(inpt):
  res = [] 
  
  for num in inpt:
    if num not in res:
      res.append(num)
  return res

print remove_duplicates([1, 2, 1, 2, 3, 3, 4, 6, 4, 6])
print remove_duplicates([10, 15, 10, 15])
print remove_duplicates([4, 4, 5, 5])

Output:

[1, 2, 3, 4, 6]
[10, 15]
[4, 5]

Once I complete a task, I often check the solution afterwards to see if anything can be done better.
However, this time around the solution appeared a bit overkill to me.

Is something wrong with the approach I went with above?

Need some help, i do not know why it is not working, it returns [4].

def remove_duplicates(lst): new_list = [] num = 0 while num < len(lst): if lst[num] not in new_list: new_list.append(lst[num]) num += 1 print new_list return new_list print remove_duplicates([4,5,5,4])

Line 9 should be unindented so that it is outside of the loop. Comment out the print statement (or remove it) that is in the loop.

1 Like

Thanks, the unindented return worked.

1 Like