Function to remove elements from a list not working (corrected)

Fredrik Lundh fredrik at pythonware.com
Mon Jun 12 12:05:19 EDT 2006


Girish Sahani wrote:

> Thanks!It worked....i wasted a lot of time trying to find a bug in my
> code...what is wrong in iterating over a list and modifying it?
> Doesnt python take the modified list every time the loop starts?

this is explained in the tutorial, under "the for statement":

     The for loop maintains an internal loop variable, and you may get
     unexpected results if you try to modify the sequence being iterated
     over in the loop (this can only happen for mutable sequence types,
     such as lists). To safely modify the list you are iterating over
     (for example, to duplicate selected items), you must iterate over
     a copy. The slice notation makes this particularly convenient:

     >>> for x in a[:]: # make a slice copy of the entire list
     ...    if len(x) > 6: a.insert(0, x)
     ...
     >>> a
     ['defenestrate', 'cat', 'window', 'defenestrate']

(see http://pytut.infogami.com/node6.html )

</F>




More information about the Python-list mailing list