When I run this:
l = [0] * 5
l[0] = 1
l[1] = 2
print(l)
I get [1, 2, 0, 0, 0]
.
But when I run this:
l = [[]] * 5
l[0].append(1)
l[1].append(2)
print(l)
then I get [[1, 2], [1, 2], [1, 2], [1, 2], [1, 2]]
.
I expected [[1], [2], [], [], []]
.
What is difference between [k]*n
and [[]]*n
?
And why do the lists share their elements one another?
Plus, how can I make 2d list without element-sharing lists more briefly than this?
l = []
for i in range(5):
l.append([])
l[0].append(1)
l[1].append(2)
print(l)
It gives [[1], [2], [], [], []]
.
Thank you.