May I loop over a changing list?

Charles G Waldman cgw at fnal.gov
Wed Sep 22 10:17:08 EDT 1999


Olaf Delgado writes:
 > Hi folks!
 > 
 > I am whondering whether the following is considered good (and,
 > more important: save) programming style in python:

No, you must never modify a list your are iterating over.

This is mentioned in the Tutorial, section 4.2:

4.2 for Statements 

 It is not safe to modify the sequence being iterated over in the loop
 (this can only happen for mutable sequence types, i.e., lists). If
 you need to modify the list you are iterating over, e.g., 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']


I think this ought to be in the FAQ, but a quick check didn't turn it
up.





More information about the Python-list mailing list