[Tutor] iterate list items as lvalue
János Juhász
janos.juhasz at VELUX.com
Mon Aug 20 08:27:19 CEST 2007
Dear Tutors!
I know a python list is a mutable object.
>>> array = [1,2,3,4,5]
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
...
>>> array
[1, 2, 3, 4, 5]
It confused me a little, so made another test.
>>> item1 = array[0]
>>> item1
1
>>> item1 = 'changed'
>>> array
[2, 4, 6, 8, 10]
>>> item1
'changed'
So I feel that, the iteration goes over on inmutable objects.
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 ?
Or is it any trick like
>>> for item in array[:]: item *= 2
...
but isn't a trick :(
>>> array
[2, 4, 6, 8, 10]
Yours sincerely,
János Juhász
More information about the Tutor
mailing list