strange behaviour with remove
brianc at temple.edu
brianc at temple.edu
Wed Jun 23 18:34:13 EDT 2004
Common newbie learning step. A variable in python is a
reference, not the actual data itself. So in "d = { 'list' : l
}", you are storing a reference to the original "l", not a new
list. Look at the following interactive session:
>>> x=['foo','bar']
>>> y=x
>>> x[1]='foo'
>>> y
['foo', 'foo']
>>> import copy
>>> y=copy.deepcopy(x)
>>> x[1]='bar'
>>> y
['foo', 'foo']
You need to use the copy module in order to make an entirely
new list.
-Brian
---- Original message ----
>Date: Sat, 19 Jun 2004 12:41:58 +0200
>From: Panard <panard at inzenet.org>
>Subject: strange behaviour with remove
>To: python-list at python.org
>
>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
>
>--
>Panard
>--
>http://mail.python.org/mailman/listinfo/python-list
More information about the Python-list
mailing list