Reputation: 1
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)
Upvotes: 0
Views: 81
Reputation: 493
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]
Upvotes: 2