How Does Python Swap Elements inside a List? -


i new python, , learned mutable , immutable objects. appears when swapping elements inside list, python creates copies of individual elements , copy them list.

enter image description here

in above example, begin n = [[1, 2], [3, 4]]. first sublist, [1, 2] occupies id# 24, , second sublist [3, 4] occupies id# 96. @ first, thought since lists mutable, after swapping, id# 24 holds [3, 4] , id# 96 holds [1, 2]. can see in test above, not case. rather, python pointing objects in manner determined our swap; first slot of list points 96 , second slot points 24.

certainly, id# of n did not change, n did not violate definition of mutable object. way sublists got swapped seems caveat. can kindly confirm or explain in more precise language?

you mistaken ids. id#24 id of list [1,2]. not memory address or id of index 0 in n.

you might want try example confirm:

>>> x = [1, 2] >>> id(x) 4332120256 >>> l = [x, 3] >>> id(l[0]) 4332120256 >>>  

Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -