Python: Removing Items From Inner And Outer For Loop Iterators
Is this piece of code potentially dangerous? Will it mess up with the inner and outer iterations? for a in listA: for b in listB: if [... something...]
Solution 1:
Is this piece of code potentially dangerous? Depends. Reducing the size of a sequence while iterating over it would give unexpected behavior.
Consider this Example
listA = [1,2,3,4]
>>> for a in listA:
listA.remove(a)
print a
Because, on removing the items, all the items beyond it, are pushed towards the left, the item that you are supposing to iterate would automatically move to the next element
First Iteration:
listA = [1,2,3,4]
^
|
_____________|
listA.remove(a)
listA = [2,3,4]
^
|
_____________|
print a
(outputs) 1
Second Iteration:
listA = [2,3,4]
^
|
_______________|
listA.remove(a)
listA = [2,4]
^
|
_______________|
print a
(outputs) 3
Third Iteration:
listA = [2,4]
^
|
_________________|
(Exits the Loop)
Solution 2:
Changing a sequence being iterated over is generally an anti-pattern in Python. While you can dance around it in specific cases, it's best to see if you can construct a new list (or dict) containing only the items you need.
Solution 3:
I agree with jknupp - removing items in a list can be more expensive than creating a new one. However, another trick is to do it backwards:
>>>l = range(5)>>>for a inreversed(l):...print a... l.remove(a)...
4
3
2
1
0
Post a Comment for "Python: Removing Items From Inner And Outer For Loop Iterators"