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

dakman at gmail.com dakman at gmail.com
Tue Oct 31 14:06:27 EST 2006


I'm not quite sure what your asking, but I'll give it a shot.

You do not have to use enumerate, you can use other methods just as
range(len(sequence)), but the reason you cannot asign a value is
because a for loop iterates a sequence meaning when you do

for a in [1, 2, 3, 4, 5]:
   ...
a is just a value pulled from the sequence iteration.

just like i and number is a value pulled from the iteration in

for i, number in enumerate(a):
  ...

(That was worded badly :/ I apologise.)
Danny Colligan 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?).
>
> >>> 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