newbie idiom question
Michael Hudson
mwh21 at cam.ac.uk
Tue Jun 22 02:36:46 EDT 1999
Alex Rice <alex at mindlube.com> writes:
> 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
If I know I'm not going to be altering the length of the list, I
generally do it like this:
for i in range(len(a)):
if is_cooked(a[i]):
a[i] = "cooked"
If the list might be changing length, then I generally do
i = 0
while i < len(a):
...
and keep track of i by hand.
HTH
Michael
> 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