python copy method alters type

Diez B. Roggisch deets at nospam.web.de
Thu May 14 09:10:12 EDT 2009


Zhenhai Zhang wrote:

> 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.

It doesn't. This must be some effect of you toying around and forgetting
some steps.

>>> import copy
>>> print "a:", a
a: ['a', 1, 3, 4]
>>> c = copy.copy(a)
>>> c[0] = "c"
>>> c[1] = 2
>>> print "c:", c
c: ['c', 2, 3, 4]


Diez



More information about the Python-list mailing list