python copy method alters type

Tim Chase python.list at tim.thechases.com
Thu May 14 09:20:46 EDT 2009


Zhenhai Zhang wrote:
> Really weired; Here is my code:
> 
>     a = ["a", 1, 3, 4]
>     print "a:", a
>    
>     c = copy(a)

Where do you get this copy() function?

   tim at rubbish:~$ python2.5
   Python 2.5.4 (r254:67916, Feb 17 2009, 20:16:45)
   >>> help(copy)
   Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
   NameError: name 'copy' is not defined

There is no "copy" in the python default namespace.  So you must 
have gotten it somewhere.  However, if you got it from the stdlib:

   >>> from copy import copy

   >>> a = ["a", 1,2,3]
   >>> b = copy(a)
   >>> b[0] = "b"
   >>> b[1] = 42
   >>> print b
   ['b', 42, 2, 3]

it would work as evidenced here.  Thus your code shows this is 
some custom copy() function which you didn't include in your 
message.  Therein lies your problem.

For shallow-copying lists, you'll usually find it written as

   b = a[:]

The "copy" module is more useful for complex data-structures and 
deep-copies.

-tkc






More information about the Python-list mailing list