strange behaviour with remove

P

Panard

Hi!

Can anyone explain this to me :
$ cat test.py
l = [ 1, 2, 3 ]
d = { 'list' : l }

for x in l :
print "rm", x
d[ 'list' ].remove( x )
print "l =", l

print d

$ python test.py
rm 1
l = [2, 3]
rm 3
l = [2]
{'list': [2]}


Why 2 isn't removed ? and why l is changing during the loop ??
Am I missing something ?

My python is 2.3.4

Thanks
 
P

Panard

Ok, I reply to myself, it's working when you add, line 3
l = [ i for i in l ]

I think the reason is that when you do a remove on d[ 'list' ] it will also
do a remove on l, because, I think, l in the dictionnary is only a
reference...

Hi!

Can anyone explain this to me :
$ cat test.py
l = [ 1, 2, 3 ]
d = { 'list' : l }

for x in l :
print "rm", x
d[ 'list' ].remove( x )
print "l =", l

print d

$ python test.py
rm 1
l = [2, 3]
rm 3
l = [2]
{'list': [2]}


Why 2 isn't removed ? and why l is changing during the loop ??
Am I missing something ?

My python is 2.3.4

Thanks
 
R

Reinhold Birkenfeld

Panard said:
Ok, I reply to myself, it's working when you add, line 3
l = [ i for i in l ]

I think the reason is that when you do a remove on d[ 'list' ] it will also
do a remove on l, because, I think, l in the dictionnary is only a
reference...

You're partially right. The list referenced to by d['list'] is the same
object as the list referenced to by l (to verify this, do a "print
d['list'] is l"). The main reason that your loop does not work is that
it modifying a list you are iterating over leads to undefined behavior.

In your solution above, you are assigning a new list to the name "l",
iterate over this list, and remove from the original list which is now
only referenced by d['list']. This is the common solution for the
problem, although there is an easier way to copy a list:

l = l[:]

Reinhold
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,201
Messages
2,571,052
Members
47,656
Latest member
rickwatson

Latest Threads

Top