[Tutor] iterate list items as lvalue

Kent Johnson kent37 at tds.net
Mon Aug 20 22:55:23 CEST 2007


Dave Kuhlman wrote:
> Consider the following:
> 
>     >>> array = [1,2,3,4,5]
>     >>> array2 = array
>     >>> array = [i * 2 for i in array]
>     >>> array
>     [2, 4, 6, 8, 10]
>     >>> array2
>     [1, 2, 3, 4, 5]
> 
> So, did you want array2 to change, or not?
> 
> Here is a solution that changes the object that both array and
> array2 refer to:
> 
>     >>> array = [1, 2, 3, 4, 5]
>     >>> array2 = array
>     >>> for idx, item in enumerate(array):
>         array[idx] = item * 2
>     >>> array
>     [2, 4, 6, 8, 10]
>     >>> array2
>     [2, 4, 6, 8, 10]
> 
> Basically, this modifies the list "in place", rather than making a
> new list from the old one.

Another way to do this is to assign to a slice of array:

array[:] = [ item*2 for item in array ]

Kent


More information about the Tutor mailing list