Home > Software design >  Why when change a dictionary from a list of dictionaries, the list also changes in Python?
Why when change a dictionary from a list of dictionaries, the list also changes in Python?

Time:08-06

A code example:

>>> y = []
>>> x = {'num':1}
>>> y.append(x)
>>> x['num']=2
>>> x['new_num']=3
>>> y
[{'num': 2, 'new_num': 3}]

Why y is also changed when I change x? Does this logic also exist in other operations in Python?

A list of values don't have this phenomenon:

>>> y = []
>>> x = 1
>>> y.append(x)
>>> x  = 1
y
[1]

CodePudding user response:

Because when you append x to y, y[0] and x still refer to the same object, you can check that by doing:

>>> x is y[0]
True

You can see that both object share the same memory address.

If you want both to be different you need to do:

y.append(x.copy())

CodePudding user response:

Because dict is reference data type. You can try do import copy and then y.append(copy.deepcopy(x))

  • Related