In a reptile combat, you need to add the dictionary to the list, the unexpected situation appeared!!! The following is a brief analysis of the situation:
1List = []2DIC = {}3 forIinchRange (5):4dic['Num'] =I5 list.append (DIC)6 Print(ID (DIC))7 Print(list)81366520969136652096Ten136652096 One136652096 A136652096 -[{'Num': 4}, {'Num': 4}, {'Num': 4}, {'Num': 4}, {'Num': 4}]
The results were unexpected, not what we thought was simple.
[{' num ': 0}, {' num ': 1}, {' num ': 2}, {' num ': 3}, {' num ': 4}]
In my own understanding is:
For example, every DIC gives a list a position, but your dic is outside the loop, and you say that each loop you give is an address, the value of DIC changes, the new loop value will overwrite the value of the previous loop, and the value of the list is changed.
Correct practice:
1List = []2 forIinchRange (5):3DIC = {}4dic['Num'] =I5 list.append (DIC)6 Print(ID (DIC))7 Print(list)81383838889136652192Ten138383408 One138384272 A138383792 -[{'Num': 0}, {'Num': 1}, {'Num': 2}, {'Num': 3}, {'Num': 4}]
The correct approach is to put DIC in the loop so that each cycle will be a new DIC, assigning a different address.
About Python, using list.append () after a loop, the data is overwritten