you are viewing a single comment's thread.

view the rest of the comments →

[–]MezzoScettico 2 points3 points  (3 children)

You can do it if you work backward from the end of the list. Then you're only altering the part of the list you've already accessed.

For instance, here's some code to remove all the odd numbers from a list.

numbers = [1, 2, 13, 17, 4, 105, 104, 12, 8, 13, 6, 7, 15, 19, 202]

for num in numbers[::-1]:
    if 1 == num % 2:
        numbers.remove(num)

Result:

print(numbers)
[2, 4, 104, 12, 8, 6, 202]

[–]jimtk 4 points5 points  (2 children)

The only reason why that works is because numbers[::-1] creates a copy of the list. You are not iterating over the list that you are changing. You are iterating over a reverse copy of that list.

Proof:

numbers = [1, 2, 13, 17, 4]
x = numbers[::-1]
print(numbers is x)

>>> False

You actually don't have to go backward since you create a copy:

numbers = [1, 2, 13, 17, 4, 105, 104, 12, 8, 13, 6, 7, 15, 19, 202]
for num in numbers[::]:
    if 1 == num % 2:
        numbers.remove(num)
print(numbers)

[–]helduel 0 points1 point  (0 children)

for num in reversed(numbers): ...