Appending in a loop creates a list of unexpected duplicates
- dictionary
- reference
- mutable
- list
The OP creates a mutable object, typically a dictionary, and an empty list. Then in a loop they modify the object and append each modified version to the list. When the loop finishes they’re surprised to discover that every list item is a duplicate of the last modified version. This is especially puzzling when they print each modified version in the loop, and it appears to be correct.
Of course, they only have one object, and they’ve simply created a list of references to that single object.
The simple solution is to create the mutable object from scratch inside the loop. Another option is to copy a template object, but deepcopy is required if the template itself contains mutable objects.