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-01 20:34:35 -0500

ikol gravatar image

updated 2015-03-01 21:36:26 -0500

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-01 21:46:57 -0500

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-01 23:06:17 -0500 )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-01 20:34:35 -0500

Seen: 998 times

Last updated: Mar 01 '15