Why can't you assign to a list in a loop without enumerate?
Danny Colligan
dannycolligan at gmail.com
Tue Oct 31 13:46:02 EST 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?).
>>> a = [1,2,3,4,5]
>>> for number in a:
... number = 10
...
>>> a
[1, 2, 3, 4, 5]
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]
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?
Thanks,
Danny
More information about the Python-list
mailing list