Alter list items within loop
Tim Harig
usernet at ilthio.net
Thu Jun 11 15:32:17 EDT 2009
On 2009-06-11, Brendan <brendandetracey at yahoo.com> wrote:
> Can someone please explain what is happening in the output below? The
> number 3 never gets printed. Does Python make a copy of a list before
> it iterates through it?:
You can see what is happening by printing the list as you work through the
loop:
>>> e = range(1,5)
>>> for i in e:
... print e
... print i
... if i == 2 :
... e.remove(i)
...
[1, 2, 3, 4]
1
[1, 2, 3, 4]
2
[1, 3, 4]
4
first loop:
i = 0
e[i] = e[0] = 1
second loop
i = 1
e[i] = e[1] = 2
third loop
i = 2
e[i] = e[2] = 4
> number 3 never gets printed. Does Python make a copy of a list before
> it iterates through it?:
No, complex types are passed by reference unless explicity copied. You can
do what you want by making an explicit copy before entering the loop:
>>> e = range(1,5)
>>> for i in e[:]:
... print e
... print i
... if i == 2 :
... e.remove(i)
...
[1, 2, 3, 4]
1
[1, 2, 3, 4]
2
[1, 3, 4]
3
[1, 3, 4]
4
More information about the Python-list
mailing list