python copy method alters type

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Thu May 14 15:12:30 CEST 2009


Zhenhai Zhang a écrit :
> Really weired; Here is my code:
> 
>    a = ["a", 1, 3, 4]
>    print "a:", a
>      c = copy(a)
>    c[0] = "c"
>    c[1] = 2
>    print "c:", c
>    print "a:",a
> 
> output as follows:
> 
> a: ['a', 1, 3, 4]
> c: ['c' '2' '3' '4']
> a: ['a', 1, 3, 4]
>
> Btw, I'm using python 2.5. I'm very curious why the copied list changed 
> data type.

I think you're not using the stdlib's copy.copy function...

Python 2.5.2 (r252:60911, Oct  5 2008, 19:24:49)
GCC 4.3.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from copy import copy
>>> a = ["a", 1, 3, 4]
>>> print a
['a', 1, 3, 4]
>>> c = copy(a)
>>> c
['a', 1, 3, 4]
>>> c[0] = "c"
>>> c[1] = 2
>>> c
['c', 2, 3, 4]
>>> a
['a', 1, 3, 4]
>>> 




More information about the Python-list mailing list