0

I want to remove duplicate elements from a list and return the list that has only unique values. Here is my code

def remove_dup(nums):
    for i in range(1, len(nums)):
        if nums[i] == nums[i-1]:
            nums.remove(nums[i])
    return nums

I am testing the code with this :

print(remove_dup([0,0,1,1,1,2,2,3,3,3,4]))

I was expecting the output to be [1,2,3,4] but I am getting [0, 1, 1, 2, 3, 3, 4]. Can anyone please explain, why?

Rashida
  • 401
  • 7
  • 18
  • 1
    Does this answer your question? [Removing duplicates in lists](https://stackoverflow.com/questions/7961363/removing-duplicates-in-lists) – SuperStormer Apr 04 '20 at 02:36
  • 1
    You’re modifying the list while iterating over it (the indexes anyway) which is nearly always a bad idea. To remove duplicates you can just turn the list into a set and then back into a list – Iain Shelvington Apr 04 '20 at 02:38
  • convert your list to `set` and then to list, simple. list(set([0,0,1,1,1,2,2,3,3,3,4])) – Minions Apr 04 '20 at 02:39

2 Answers2

1

Because you shouldn't increase i in those iterations when an element is removed. This makes you jump two elements ahead.

foreignvol
  • 681
  • 2
  • 7
  • 15
0

Convert your list to a set like so:

my_list = [0, 1, 1, 2, 3, 3, 4]
print(list(set(my_list)))

Output:

[0, 1, 2, 3, 4]
Joshua Hall
  • 332
  • 4
  • 15