Behavior of lists in python during assignment

<>

This question already has an answer here:

Answers


try this:

a = gates[:]
b = a[:]

these will make a copy of gates and a lists


All of them are references to the same object, so modifying any one of them will affect all references:

>>> gates=[16, 16, 24, 24, 24, 27, 32, 32, 32, 32, 32, 32, 40, 40, 40, 56, 56, 64, 96];
>>> import sys
>>> sys.getrefcount(gates)  #reference count to the object increased
2
>>> a = gates
>>> sys.getrefcount(gates)  #reference count to the object increased
3
>>> b = a
>>> sys.getrefcount(gates)  #reference count to the object increased 
4

If you want a new copy then assign the new variables to a shallow copy using [:]:

>>> a = [1, 2, 3]
>>> b = a[:]
>>> a[0] = 100
>>> a
[100, 2, 3]
>>> b
[1, 2, 3]

If the list contains mutable objects itself then use copy.deepcopy.


Need Your Help

the true implementation of MVC in JAVA

java model-view-controller observer-pattern

From week I have been searching of a true explanation and implementation of MVC using java, but something i have noticed is that every one implement it differently, so I would be grateful if you gi...

How do I create a wx.Image object from in-memory data?

python wxpython wxwidgets

I'm writing a GUI application in Python using wxPython and I want to display an image in a static control (wx.StaticBitmap).