newbie idiom question

ivnowa at ivnowa at
Tue Jun 22 02:47:24 EDT 1999

On 21 Jun 99, Alex Rice wrote:

> Something I keep getting tripped up about is that objects being
> iterated in "for" statements cannot be modified.
> I keep trying to do this:
>       >>> eggs = [1,2,3]
>       >>> for spam in eggs:
>       ...	spam = 'cooked'
>       ...
>       >>> eggs
>       [1, 2, 3]
>       >>> 
> 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:

> Understood, but what if you want to modify each element in a list?
> What's the best way to do this in terms of speed and elegance? I guess
> I just haven't seen a good example of this yet in Python

> What I'm unfortunately used to is this, in Perl:
>       @eggs = (1,2,3);
>       foreach $spam (@eggs) {
> 	$spam = 'cooked'; 
>       }
>       print "@eggs";
>       >>> cooked cooked cooked

An unwelcome side effect, methinx. You can use range:

for i in range(len(eggs)):
    eggs[i] = 'cooked'

Since the list you're iterating over is the same as the list you're 
modifying, it may be wise to use a slice (not in this particular 
case, but in general):

for i in range(len(mylist[:])):
    if mylist[i] == 'ham':
        mylist[i:i] = ['eggs']  # insert something

You can also use map:

eggs = map(lambda s: 'cooked', eggs)

But this can get difficult for complex lambdas, and it doesn't change 
the list in place.

Hans Nowak (ivnowa at

More information about the Python-list mailing list