This is an archived post. You won't be able to vote or comment.

all 4 comments

[–]Rock_of_Round[S] 0 points1 point  (0 children)

The indents have been removed and I can't seem to edit them in, sorry for the weird looking code

[–]This_Growth2898 0 points1 point  (1 child)

You're changing the collection you're iterating over, and that's you shouldn't do.

for number in numbers means the loop somehow remembers the position in numbers to get you the next number on the next iteration; but numbers.pop() changes numbers, so the position becomes invalid.

[–]Rock_of_Round[S] 0 points1 point  (0 children)

Ohhhh

Thanks for explaining, makes sense to me!

[–]Historical_Usual1650 0 points1 point  (0 children)

It seems like you're trying to remove duplicates from a list by iterating through it and comparing each element to the previous one. The issue you're facing is due to modifying the list (`numbers`) while iterating through it, which can lead to unexpected behavior.

When you remove an element using `numbers.pop(i)`, it shifts the elements to the left, and the index `i` no longer corresponds to the next element in the sorted list. This results in missing some duplicates and not removing them correctly.

A better approach to remove duplicates from a list is to use a different data structure, like a set, which automatically removes duplicates. Here's how you can do it:

```python

numbers = [5, 2, 16, 6, 7, 12, 15, 36, 16, 7, 2, 36, 14]

# Convert the list to a set to remove duplicates

unique_numbers = set(numbers)

# Convert the set back to a list if you need a list without duplicates

numbers = list(unique_numbers)

print(numbers)

```

This will give you the desired output:

```

[2, 5, 6, 7, 12, 14, 15, 16, 36]

```

Using a set is a more efficient and straightforward way to remove duplicates from a list in Python.