python copy method alters type

Z

Zhenhai Zhang

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.

Thanks,

Zhenhai
 
D

Diez B. Roggisch

Zhenhai said:
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
 
B

Bruno Desthuilliers

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]
 
G

greg

Zhenhai said:
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).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top