Strange output when multiplying a list

here is my code :

L=[[1]*5]*5

print(L)

for i in range(4):
for j in range(4):
L[i][j]=0

print(L)

Why the last line in the output is

[0, 0, 0, 0, 1]

rather than

[1, 1, 1, 1, 1]

I got this output with different interpreters

thanks !

Because range(4) means 0, 1, 2, 3.
4 is excluded from range(4).

Note: Please use “</>” in the formatting toolbar to format your code properly next time.

Thank you 5DN1L for replying,

But my list L is of size 5,
and I used range(4),
so the last line should remain the same
(i.e. [1, 1, 1, 1, 1] )
but it changes
(i.e. [0, 0, 0, 0, 1] )
which I find strange
(I used different online interpreters)

Ah ok. You may find the answer to this similar question here:
https://stackoverflow.com/questions/6688223/python-list-multiplication-3-makes-3-lists-which-mirror-each-other-when

2 Likes

Thank you very much

It helps