0

I have a problem when working on jupyter notebook using python 3.6.3. when I write following code in one cell and execute:

x=dict()
y=dict()
for j in range(3):
    x[j]=str(j)
y=x
for i in range(2):
    y[i]=5

This will give me the result that both x and y being the same as {0:5,1:5,2:'2'}, which is weird to me since I expect x={0: '0', 1: '1', 2: '2'} and y = {0: 5, 1: 5, 2: '2'}. I don't understand why the above code will change x as well while I assign new values to y Thanks

DSCH
  • 2,146
  • 1
  • 18
  • 29
  • 2
    Sounds like you could use a [quick guide to what assignment actually does in Python](https://nedbatchelder.com/text/names.html). – user2357112 Nov 27 '17 at 06:31
  • your 5th line says is all: "y it x". After that anything you do to `y` will also be done to `x` – Paul H Nov 27 '17 at 06:32

1 Answers1

0

In line 5 you make y point to the exact same dictionary as x, so they are no longer two separate dicts. So what ever you will assign to x will be assigned to y and vice-versa.

DSCH
  • 2,146
  • 1
  • 18
  • 29
  • Thanks, Will this property only affect dictionary or some other data structure in Python? – Yigong Liu Nov 28 '17 at 05:05
  • All mutable types behave similarly. You can look up this answer https://stackoverflow.com/a/8056598/5751251. Basically lists, sets, dicts and bytearrays are mutable. – DSCH Nov 28 '17 at 05:51