python - Shallow copy: why is list changing but not a string? -
i understand when shallow copy of dictionary, make copy of references. if this:
x={'key':['a','b','c']} y=x.copy()
so reference of list ['a','b','c'] copied y. whenever change list ( x['key'].remove('a')
example), both dict x , y change. part understand. when consider situation below:
x={'user':'admin','key':['a','b','c']} y=x.copy()
when y['user']='guest'
, x['user'] not change, list still shares same reference. question makes string different list? mechanism behind this?
you're doing 2 different things. when do
x['key'].remove('a')
you mutate object x['key']
references. if variable references same object, you'll see change point of view, too:
however, in second case, situation different:
if do
y['user']='guest'
you rebind y['user']
new object. of course not affect x['user']
or object references.
this has nothing mutable vs. immutable objects, way. if did
x['key'] = [1,2,3]
you wouldn't change y['key']
either:
see interactively on pythontutor.com.
Comments
Post a Comment