Why does append[] overwrite/clobber every existing element of a list with the one that was just appended?edit
- append_list_clobber
asked 2015-03-02 03:34:35 +0100
ikol
143 2 9 16
143 2 9 16
updated 2015-03-02 04:36:26 +0100
calc314
4161 21 48 112
4161 21 48 112
M = []
L = [0 for i in range[10]]
print L
M.append[L]
print M
L[0] +=1
L[7] +=1
print L
M.append[L]
print M
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
[1, 0, 0, 0, 0, 0, 0, 1, 0, 0]
[[1, 0, 0, 0, 0, 0, 0, 1, 0, 0], [1, 0, 0, 0, 0, 0, 0, 1, 0, 0]]
edit retag flag offensive close merge delete
add a comment
answered 2015-03-02 04:46:57 +0100
calc314
4161 21 48 112
4161 21 48 112
This is really a matter of how Python handles assignments of lists. In both of your append commands, Python is pointing to the same list L. This is why the first list that you append appears to change. The append command here does not actually make a new copy of the list L and then put it in M. Instead, both append commands put references to the original list L in the new list M. To append a new copy of the list L, you could use: M.append[copy[L]] or M.append[L[:]].
edit flag offensive delete link more
Comments
That's very helpful, thanks!
[ 2015-03-02 06:06:17 +0100 ]edit
add a comment