Why can't you assign to a list in a loop without enumerate?
Duncan Booth
duncan.booth at invalid.invalid
Tue Oct 31 14:04:44 EST 2006
"Danny Colligan" <dannycolligan at gmail.com> wrote:
> 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?).
No. There is no copying involved.
Before the assignment, number is a reference to the object to which the ith
element of the list also refers. After the assignment you have rebound the
variable 'number' so it refers to the value 10. You won't affect the list
that way.
> 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?
There is no copying going on. It returns the value itself, or at least a
reference to it.
> Also, is there any way to assign to a list in a for loop (with
> as little code as used above) without using enumerate?
a[:] = [10]*len(a)
or more usually something like:
a = [ fn(v) for v in a ]
for some suitable expression involving the value. N.B. This last form
leaves the original list unchanged: if you really need to mutate it in
place assign to a[:] as in the first example, but if you are changing all
elements in the list then you usually want a new list.
More information about the Python-list
mailing list