Behavior of lists in python during assignment


This question already has an answer here:


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
>>> a = gates
>>> sys.getrefcount(gates)  #reference count to the object increased
>>> b = a
>>> sys.getrefcount(gates)  #reference count to the object increased 

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

Constants and Maintainability

design-patterns constants

I have a simple question that relates to good programming practices. Specifically, I am curious to the proper way to handle grouping constants. In school, they taught us to place our constants at...

What's the best visual merge tool for Git?

git version-control merge

Title says it. What's the best tool for viewing and editing a merge in Git? I'd like to get a 3-way merge view, with "mine", "theirs" and "ancestor" in separate panels, and a fourth "output" panel.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.