3

I want to create a matrix of list, but when I create the lists inside the matrix it created a linked list, and I don't need that.

A=[[{}]*3]*3
result: [[{}, {}, {}], [{}, {}, {}], [{}, {}, {}]]
A[0][2]['h1']=1
result: [[{'h1': 1}, {'h1': 1}, {'h1': 1}],
 [{'h1': 1}, {'h1': 1}, {'h1': 1}],
 [{'h1': 1}, {'h1': 1}, {'h1': 1}]]

Anyone knows how to avoid this? I need a list inside each field of the matrix.

silgon
  • 6,890
  • 7
  • 46
  • 67

1 Answers1

10

You are initializing A with 3 references to the same list, and each of those lists is being initialized with 3 references to the same dictionary. Instead, try explicitly calling a constructor for each sublist and dictionary:

>>> A = [ [{} for _ in range(3) ] for _ in range(3) ]
>>> A[0][2]['h1']=1
>>> A
[[{}, {}, {'h1': 1}],
 [{}, {}, {}],
 [{}, {}, {}]
]

As a side note, "linked list" generally refers to the data structure of the same name, rather than the case where you have multiple references to the same object.

mdml
  • 22,442
  • 8
  • 58
  • 66