0

I have to remove the duplicates in a list using Python 3 language. What is wrong with this code?

numbers = [1, 2, 2, 2, 2, 2, 2, 2, 3, 4, 5] 
for num in numbers:
    if numbers.count(num) > 1:
        numbers.remove(num)
print(numbers) 
  1. please tell how do I solve this problem??
dejanualex
  • 3,872
  • 6
  • 22
  • 37
  • 3
    if you don't care about the order: `list(set(numbers))` – FObersteiner Aug 20 '20 at 09:42
  • 3
    "*What is wrong with this code?*": don't modify the iterable while you iterate over it. strange things will happen. – FObersteiner Aug 20 '20 at 09:43
  • 1
    *Never ever* modify a structure you're iterating on. This is the same problem as in this post: https://stackoverflow.com/questions/63193121/why-does-my-code-for-removing-the-even-numbers-from-the-beginning-of-a-list-not/63194113#63194113 – qouify Aug 20 '20 at 09:45
  • Speaking out of experience: Never append to a structure you are working on either. That easily creates an infinite loop! – Dustin Aug 20 '20 at 09:49
  • 3
    Does this answer your question? [Removing from a list while iterating over it](https://stackoverflow.com/questions/6500888/removing-from-a-list-while-iterating-over-it) – MisterMiyagi Aug 20 '20 at 09:51

1 Answers1

2

Generally speaking, don't append or remove values from a list in a loop like that.

There is a nice pythonic way to do it: Turn it into a set (only has 1 item of each) and then transform that set into a list.

numbers = [1, 2, 2, 2, 2, 2, 2, 2, 3, 4, 5]
numbers = list(set(numbers))
print(numbers)
>>> [1, 2, 3, 4, 5]
Dustin
  • 483
  • 3
  • 13