I have a list
a = ["a", "b", "c", "d", "e"]
I want to remove elements in this list in a for loop like below:
for item in a:
print item
a.remove(item)
But it doesn't work. What can I do?
解决方案
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(0)
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.