Ankit Seth
Ankit Seth

Reputation: 1

removing duplicate numbers in a list using Python 3.8.5

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??

Upvotes: 0

Views: 81

Answers (1)

Dustin
Dustin

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

Related Questions