0

I am trying to populate a 2d list with lists (making it a 3d list). My code is of the form:

a=[[],[],[]]
toydata1 = [1,2,3]
toydata2 = [4,5,6]
a[0].append(toydata1)
a[1].append(toydata2)

after this, the value of a is

[[[1, 2, 3]], [[4, 5, 6]], []]

as expected. However if I use

a=[[]]*3
toydata1 = [1,2,3]
toydata2 = [4,5,6]
a[0].append(toydata1)
a[1].append(toydata2)

the value of a is

[[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4,5,6]]]

Can someone explain why append behaves differently based on how I initialize a? Also, why is it appending to all list elements in the second case? [[]]*3 == [[],[],[]] returns True, so I am guessing they have the same value.

I am running Python 3.7.4 on Ubuntu 18.04 if that helps.

user1637744
  • 13
  • 2
  • 5

0 Answers0