[Tutor] iterate list items as lvalue

Alan Gauld alan.gauld at btinternet.com
Mon Aug 20 12:11:50 CEST 2007


"János Juhász" <janos.juhasz at VELUX.com> wrote

> So I can modify any item in it.
> >>> for index in range(len(array)): array[index] *= 2
> ...
> >>> array
> [2, 4, 6, 8, 10]
>
> So I typed this:
> >>> for item in array: item *= 2

This is equivalent to

index = 0
while index < len(array):
     item = array[index]   # references the content of the array
     item =  item * 2        # assigns a new value to item, no change 
to the array content
     index +=1

> It confused me a little, so made another test.
> >>> item1 = array[0]
> >>> item1
> 1
> >>> item1 = 'changed'
> >>> array
> [2, 4, 6, 8, 10]
> >>> item1
> 'changed'

This shows that you can assign item1 to the array content and you
can change the assignment to something else, all without affecting
the list itself

> But how can I iterate the iterate the items as mutable object,
> like the pointers in C ?
> Is the only way to manage the iteration with indexes ?

If you want to change the contents of the array then you need to
access the array, so yes you need the index.

> Or is it any trick like
> >>> for item in array[:]: item *= 2

That only creates a new temporary list referencing the same
objects as the original  it doesn't change anything in the existing
one.

The normal way to change a single item, in a lst is to use
the index. If you are doing bulk changes use a list
comprehension to build a new list:

>>> array = [1,2,3,4,5]
>>> print array
[1, 2, 3, 4, 5]
>>> array[2] = 9
>>> print array
[1, 2, 9, 4, 5]
>>> array = [n*2 for n in array]
>>> print array
[2, 4, 18, 8, 10]
>>>

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 




More information about the Tutor mailing list