Why can't you assign to a list in a loop without enumerate?

Tim Chase python.list at tim.thechases.com
Tue Oct 31 20:43:08 CET 2006


> In the following code snippet, I attempt to assign 10 to every index in
> the list a and fail because when I try to assign number to 10, number
> is a deep copy of the ith index (is this statement correct?).

Sorta...just like with function parameters, there are mutables 
and immutables.

>>>> a = [1,2,3,4,5]
>>>> for number in a:
> ...     number = 10
> ...
>>>> a
> [1, 2, 3, 4, 5]

Just as with a function (currently discussed on another thread 
recently), you have the following behavior:

 >>> def a(x):
...	x = 42
...
 >>> deb b(x):
...	x.append(42)
...
 >>> g = 1
 >>> h = [1]
 >>> a(g)
 >>> b(h)
 >>> g
1
 >>> h
[1, 42]


you have similar behavior:

 >>> a = [[1],[2],[3],[4],[5]]
 >>> for thing in a:
...     thing.append(10)
...
 >>> a
[[1, 10], [2, 10], [3, 10], [4, 10], [5, 10]]

Lists/sets/etc are mutable.  Strings, numbers,

> So, I have to resort to using enumerate to assign to the list:
> 
>>>> for i, number in enumerate(a):
> ...     a[i] = 10
> ...
>>>> a
> [10, 10, 10, 10, 10]

This would commonly be written with a list comprehension:

a = [10 for _ in a]

or

a = [10] * len(a)

or, if that was a general case of something more specific with 
some "if" brains behind it, you can do things like

a = [odd(v) and 10 or v for v in a]

to only change them to 10 where the value is odd.

> My question is, what was the motivation for returning a deep copy of
> the value at the ith index inside a for loop instead of the value
> itself?  Also, is there any way to assign to a list in a for loop (with
> as little code as used above) without using enumerate?


As stated above, it returns the item...if it's mutable, you can 
mutate it.  If it's an immutable (like your numbers), you just 
change the variable in the local scope of the loop.


-tkc







More information about the Python-list mailing list