list traversal and remove

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Thu Jan 31 04:55:15 EST 2008


On Wed, 30 Jan 2008 23:49:46 -0800, digisatori at gmail.com wrote:

> I supposed the below code will print seven 2 and generate the list li
> without 2.
> Strangely it only print  four 2. If you change the number of 2 in the
> list, the results are all beyond expectation. I know the other way to
> achieve the expected goal, but why this is happening? Could somebody
> enlight me?

Do not modify a list at the same time that you are traversing it.

If you look at the archives (say, on Google Groups, or any number of 
other places), this topic was just discussed yesterday and earlier today.

See the thread with subject line:

"Removal of element from list while traversing causes the next  element 
to be skipped"

As for why it is happening... you have code that looks like this:

for x in li:
    if x == 2:
        print x
        li.remove(x)


Consider that "under the hood", the for-loop looks something like this:

i = 0
while i < the length of the list:
    set x equal to the item in the i-th position
    execute the loop block of code
    i += 1

If you start deleting or inserting items in the middle of the loop, the 
index won't be pointing where you expect.



-- 
Steven



More information about the Python-list mailing list