I have a list of dicts for storing data. When I make change in one dict, that change is reflected in all dicts.
students = [{"marks": [], "subjects": 0}]*3
specific_student = 2
print("Before updating", students)
students[specific_student]["marks"].append(50)
students[specific_student]["subjects"] += 1
print("After updating", students)
I was expecting that, only last dict will get updated. but surprisingly all dicts were changed.
The obtained result of above program is
Before editing [{'subjects': 0, 'marks': []}, {'subjects': 0, 'marks': []}, {'subjects': 0, 'marks': []}]
After editing [{'subjects': 1, 'marks': [50]}, {'subjects': 1, 'marks': [50]}, {'subjects': 1, 'marks': [50]}]
But the expected result(only dict at position 2 gets changed) was
Before editing [{'subjects': 0, 'marks': []}, {'subjects': 0, 'marks': []}, {'subjects': 0, 'marks': []}]
After editing [{'subjects': 0, 'marks': []}, {'subjects': 0, 'marks': []}, {'subjects': 1, 'marks': [50]}]
Can some one explain this strange behavior and suggest a solution to obtain the expected result?