Ask Your Question
0

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

asked 10 years ago

ikol gravatar image

updated 10 years ago

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]]
Preview: (hide)

1 Answer

Sort by » oldest newest most voted
2

answered 10 years ago

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[:]).

Preview: (hide)
link

Comments

That's very helpful, thanks!

ikol gravatar imageikol ( 10 years ago )

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: 10 years ago

Seen: 18,926 times

Last updated: Mar 02 '15