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:

pythontutor visualization pythontutor visualization 2

however, in second case, situation different:

pt vis 3

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:

pt vis 4

see interactively on pythontutor.com.


Comments

Popular posts from this blog

php - get table cell data from and place a copy in another table -

javascript - Mootools wait with Fx.Morph start -

php - Navigate throught databse rows -