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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With