Ask Your Question
0

Why does append() overwrite/clobber every existing element of a list with the one that was just appended?

asked 2015-03-02 03:34:35 +0100

ikol gravatar image

updated 2015-03-02 04:36:26 +0100

calc314 gravatar image
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

1 Answer

Sort by ยป oldest newest most voted
2

answered 2015-03-02 04:46:57 +0100

calc314 gravatar image

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!

ikol gravatar imageikol ( 2015-03-02 06:06:17 +0100 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2015-03-02 03:34:35 +0100

Seen: 18,613 times

Last updated: Mar 02 '15