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

java - Run spring boot application error: Cannot instantiate interface org.springframework.context.ApplicationListener -

reactjs - React router and this.props.children - how to pass state to this.props.children -

Excel VBA "Microsoft Windows Common Controls 6.0 (SP6)" Location Changes -