0

I have this code:

s = [64, 128]
a = [[]] * len(s)
print(a)
print(a[0])
a[0].append([1,2])
print(a)

If I run it, I get this:

[[], []]
[]
[[[1, 2]], [[1, 2]]]

So a is a list of list, initialized with two empty lists.

I append the list [1,2] to a[0], which, in my intentions, would be the first empty list.

I was expecting a to be equal to [ [ [1,2] ], [] ].

Is there anyone who can help me?

1) Why did I get that [ [1,2], [1,2] ]?

2) How can I assign [1,2] to the first list in the list of lists a?

Antonio Sesto
  • 2,868
  • 5
  • 33
  • 51
  • @MattR this is yet another story; it inserts a third list. Don't confuse OP even more. – Ma0 Nov 30 '17 at 13:59
  • @Antonio It's basically the same list repeated thrice when you do [[]]*3. So when you alter one inner list, all will be altered. Basically changing this condition to a =[[],[],[]] will fix it. You can also generate innerlists within a loop to fix it. – Rusty Nov 30 '17 at 14:10
  • Yes, I have read the original question pointed out by Kevin and understood why. Thanks. I searched it but could not find that specific question: sorry for repeating. – Antonio Sesto Nov 30 '17 at 14:24

0 Answers0