1

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?

Sreeragh A R
  • 2,871
  • 3
  • 27
  • 54
  • 1
    It's all the same dict, repeated three times. It's because of how you create the list (with `* 3`), it just creates a list with three times the same reference. See questions like https://stackoverflow.com/questions/2785954/creating-a-list-in-python-with-multiple-copies-of-a-given-object-in-a-single-lin for better ways. – RemcoGerlich Sep 18 '19 at 10:11

1 Answers1

1

You need to use .copy() onto your list, else it would be a link of your dict and not a new dict with the same values.
Note that you need to use .copy() on EVERY dict and list you want to copy, even those in your dict/list

Calvin-Ruiz
  • 173
  • 1
  • 1
  • 9