list - Variable assignment and modification (in python) -
when ran script (python v2.6):
a = [1,2] b = a.append(3) print >>>> [1,2,3] print b >>>> [1,2,3] i expected print b output [1,2]. why did b changed when did change a? b permanently tied a? if so, can make them independent? how?
memory management in python involves private heap memory location containing python objects , data structures.
python's runtime deals in references objects (which live in heap): goes on python's stack references values live elsewhere.
>>> = [1, 2] 
>>> b = 
>>> a.append(3) 
here can see variable b bound same object a.
you can use is operator tests if 2 objects physically same, means if have same address in memory. can tested using id() function.
>>> b >>> true >>> id(a) == id(b) >>> true so, in case, you must explicitly ask copy. once you've done that, there no more connection between 2 distinct list objects.
>>> b = list(a) >>> b >>> false 
Comments
Post a Comment