deleting elements from a list in a for loop
flupke at nonexistingdomain.com
Fri Oct 29 16:54:04 CEST 2004
Benjamin Niemann wrote:
> If it doesn't matter in which order you scan the list:
> for idx in xrange(len(el), -1, -1):
> element = el[idx]
> if ....:
> del el[idx]
> By running from end to start of the list, a "del" won't affect later
> iterations of the loop.
> Generally: you shouldn't modify a list while doing a "for a in el:" -
> this just causes confusion (as you've already seen ;)
Scan order doesn't matter so i could also use this sollution.
The for line should be "for idx in xrange(len(el)-1, -1, -1):"
for it to work.
Any, also a great sollution, thanks!
More information about the Python-list