0

removes the duplicates in a list

numbers = [5, 8, 5, 4, 4, 7, 7, 3, 1, 8]
numbers.sort()
print(numbers)
value = 0

for x in numbers:
   if value == x:
       numbers.remove(x)
  else:
      value = x
print(numbers)

it's working for 4 and 7 but not for 5 and 8

output:

[1, 3, 4, 4, 5, 5, 7, 7, 8, 8]
[1, 3, 4, 5, 5, 7, 8, 8]

Note: I haven't seen the solution yet. It will be better if you point out the bug instead of posting the whole code

Shreyas Prakash
  • 604
  • 4
  • 11
  • 3
    The bug is in modifying the list that is being iterated over. Each call to `remove` makes the list shorter and causes the for-loop to skip one element. – mportes Oct 20 '21 at 07:29
  • 1
    Modifying a container while iterating on it causes undefined behaviour. It does not raise any error, yet it is incorrect code. The Pythonic way would be `sorted(set(numbers))`: `set` ensures no duplicates, and `sorted` produces a sorted list. – Serge Ballesta Oct 20 '21 at 07:31
  • my thanks and appreciation. – junayed_i_said Oct 20 '21 at 07:32

0 Answers0