newbie idiom question

Terry Reedy tjreedy at udel.edu
Tue Jun 22 02:52:22 EDT 1999


In article <m3emj4yezq.fsf at monsoon.swcp.com>, alex at mindlube.com says...
>
>Something I keep getting tripped up about is that objects being
>iterated in "for" statements cannot be modified.

It depends on whether the objects are mutable or not.

>I keep trying to do this:
>
>      >>> eggs = [1,2,3]
>      >>> for spam in eggs:
>      ...       spam = 'cooked'
>      ...
>      >>> eggs
>      [1, 2, 3]
>      >>> 

Modifying the list by replacement is relatively easy.

eggs = [1,2,3]
for i in range(len(eggs)): eggs[i] = 'cooked'

>The tutorial says this:
>
>      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']

This applies to insertions and deletions.  Without making a copy, the result 
in difficult to predict.

>Understood, but what if you want to modify each element in a list?

Do you actually want to change the elements (leaving the list the same) or 
change the list?

Terry J. Reedy





More information about the Python-list mailing list