newbie idiom question
Alex Rice
alex at mindlube.com
Tue Jun 22 01:35:21 EDT 1999
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:
>>> 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']
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
Thanks,
Alex Rice
More information about the Python-list
mailing list