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] 

python variables

>>> b = 

python variables

>>> a.append(3) 

python variables

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 

python variables


Comments

Popular posts from this blog

How to check data type in C++? -

javascript - Is getTimezoneOffset() stable during daylight saving transition? -

sql server - SQL Query returns one result, does not return 0 or NULL result -