Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

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

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]]

click to hide/show revision 2
No.2 Revision

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

M = []

[]

L = [0 for i in range(10)]

range(10)] print L

M.append(L) print L

M L[0] +=1

M.append(L)

L[7] +=1 print L

M.append(L) print M

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, 0]]

0]]

[1, 0, 0, 0, 0, 0, 0, 1, 0, 0]

0]

[[1, 0, 0, 0, 0, 0, 0, 1, 0, 0], [1, 0, 0, 0, 0, 0, 0, 1, 0, 0]]

0]]