0

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.

dbld
  • 998
  • 1
  • 7
  • 17
  • 1
    `l = [[]]` is a list containg a list. So `l[0].append(1)` appends the element 1 to the list inside the list. Therefore `[[1]]`. `l[0].append(2)` apends the element 2 to the list 0 inside list. Thereafter `[[1,2]]` – jamoreiras Aug 22 '21 at 02:20
  • `[[]] * 5` gives you five identical references to _the same list_. If you append to one of them, they all get appended, because _they're the same object_. – John Gordon Aug 22 '21 at 02:27

0 Answers0