0

sorry to ask this 'stupid' question, but i'm buffled with this problem for the past hours. I've been coding python for quite a while, and never had this kind of problem, but my laptop got stolen, so I installed python 3.3 on another computer. And when today I tried to do something with list cloning, i keep getting problem, so finally i tried this:

a = [[0, 1, 2],[-1, 0, 1],[-2, -1, 0]]
m = a[:]
m[1][1] = 'x'
print(m,a)

and the result is:

[[0, 1, 2], [-1, 'x', 1], [-2, -1, 0]]  [[0, 1, 2], [-1, 'x', 1], [-2, -1, 0]]

how come??? m should be a copy of a. I tried to id(a) and id(m) and they both shows different result. But still it results like that. Probably something wrong with my compiler? Please advise.

P.S. I've read the posts mentioned before I post this question. I know how to copy/clone a list. And usually I don't have any problems with it, until today. And perhaps to clarify my question, it's not how to correct it (since I have already work around it to get the correct results), but why the code behave like that when theorytically m = a[:] would result a new list with same value as a, and not just referring the same list as a.

P.P.S. Sorry, I read the posts mentioned again once more, and I found the answer there: [:] doesn't work for nested list. I didn't fully get/understand the term 'nested list' at first time read (English is not my mother language). Case closed. Thanks.

Lingson
  • 71
  • 1
  • 3

1 Answers1

1

The compiler is right.

If you check id(m[1]) and id(a[1]), you may find they refer to the same object.

I think the reason is that the list a and m just store reference to other objects, something like pointers in C++.

I should say this is a notice-worthy case when we consider making a replicate of list using slicing. Pretty good example!

Ray
  • 2,472
  • 18
  • 22