Getting rid of duplicates (beginner course)

In the tutorial Mosh loops over a list of numbers and copies the uniques into a new variable. I wrote a different solution to get rid of the duplicates in the list itself, but I don’t understand why it doesn’t work. Can someone tell me why some duplicates are getting removed, but others won’t? I wrote this:

numbers = [2, 2, 4, 1, 3, 4, 2, 6, 1, 1, 1, 1]

for number in numbers:

  • if numbers.count(number) > 1:*
  •    numbers.remove(number)*


the output that I’m getting is:
[3, 4, 2, 6, 1, 1, 1]

You shouldn’t modify the list you are iterating over in a for loop. Depending on how the iterator is implemented you can have all sorts of weird behaviour if you do so.

1 Like

The alternative, you can create a set based on that array. Set remove duplicates.

Hey, use sets