How to remove list elements in a for loop in Python? [duplicate]

You are not permitted to remove elements from the list while iterating over it using a for loop.

The best way to rewrite the code depends on what it is you’re trying to do.

For example, your code is equivalent to:

for item in a:
    print(item)
a[:] = []

Alternatively, you could use a while loop:

while a:
    print(a.pop())

I’m trying to remove items if they match a condition. Then I go to next item.

You could copy every element that doesn’t match the condition into a second list:

result = []
for item in a:
    if condition is False:
        result.append(item)
a = result

Alternatively, you could use filter or a list comprehension and assign the result back to a:

a = filter(lambda item:... , a)

or

a = [item for item in a if ...]

where ... stands for the condition that you need to check.

Leave a Comment