python copy method alters type

greg greg at cosc.canterbury.ac.nz
Fri May 15 23:15:48 EDT 2009


Zhenhai Zhang wrote:

> a: ['a', 1, 3, 4]
> c: ['c' '2' '3' '4']

The lack of commas here suggests that c is actually
a numpy array rather than a list.

Did you import copy from Numeric or numpy, by any
chance?

The following experiment reproduces your result:

 >>> import numpy
 >>> a = ['a', 1, 2, 3]
 >>> c = numpy.copy(a)
 >>> print c
['a' '1' '2' '3']

What's happening here is that numpy.copy is using
the type of the first element to decide the type
of the whole array, and then converting the rest
of the elements to that type.

If you want the standard Python copying behaviour,
use copy.copy instead (or use a[:], which might
be slightly more efficient).

-- 
Greg



More information about the Python-list mailing list