Mar-24-2020, 06:59 PM
Moving the dict instantiation into the loop fixed it. Previously, you were referencing the same dict multiple times in a list. That means any update to the dict will update every reference in the list because they all get their information from the same memory location.
Inside the loop, the dict instantiation creates a new dict stored at a different memory location each time. Even though you're appending the same variable to the list, that variable has a different reference every time the loop runs.
Inside the loop, the dict instantiation creates a new dict stored at a different memory location each time. Even though you're appending the same variable to the list, that variable has a different reference every time the loop runs.
out= [] for x in range(10): example = {} out.append(example) print(id(example))
Output:52431536
55345824
55345728
55345680
55346208
55347456
55346256
55346304
55346352
55346400
Compared to the original:out = [] example= {} for x in range(10): out.append(example) print(id(example))
Output:55345968
55345968
55345968
55345968
55345968
55345968
55345968
55345968
55345968
55345968