0

I have a list of dictionary entries which I first initialize and then want to change only 2 out of the 9 list entries. But after changing one of the entries, all the entries on the list have been changed.

    In [1]: cell_init = {'state':False, 'age':0}

    In [2]: cell_list = []

    In [3]: n = 3

    In [4]: for index in range(n * n):
       ...:     cell_list.append(cell_init)
       ...:     

    In [6]: cell_list
    Out[6]: 
    [{'age': 0, 'state': False},
     {'age': 0, 'state': False},
     {'age': 0, 'state': False},
     {'age': 0, 'state': False},
     {'age': 0, 'state': False},
     {'age': 0, 'state': False}, 
     {'age': 0, 'state': False},
     {'age': 0, 'state': False},
     {'age': 0, 'state': False}]

    In [8]: cell_entry = cell_list[2]

    In [9]: cell_entry
    Out[9]: {'age': 0, 'state': False}

    In [10]: cell_entry['state'] = True

    In [11]: cell_list
    Out[11]: 
    [{'age': 0, 'state': True},
     {'age': 0, 'state': True},
     {'age': 0, 'state': True},
     {'age': 0, 'state': True},
     {'age': 0, 'state': True},
     {'age': 0, 'state': True},
     {'age': 0, 'state': True},
     {'age': 0, 'state': True},
     {'age': 0, 'state': True}]

Why did all of these entries get changed?

  • 1
    You are appending **one** dict object, over and over again. Appending a list does not create a copy, see the duplicate on how to properly copy a dict. Or create a new dict object each loop iteration rather than once. – Martijn Pieters Jul 04 '17 at 16:55
  • (and apologies for the dict / list mixup, had to wait to clear some train tunnels before I could correct). – Martijn Pieters Jul 04 '17 at 17:01
  • Figured it out. When I initialized the list, I put the same object on the list 9 times. So changing one of them changed all of them. – Richard Williams Jul 04 '17 at 17:28

0 Answers0