Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matrix of lists - Python [duplicate]

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.

like image 322
silgon Avatar asked Jun 25 '26 10:06

silgon


1 Answers

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.

like image 164
mdml Avatar answered Jun 28 '26 00:06

mdml



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!