Cloning a List in Python
April 14, 2008 by Isaac
As far as I know there is no official way to clone a list in Python. This is desirable at times because normal variable assignment of lists is just a reference copy. For example:
>>> listA = ['A', 'B', 'C', 'D'] >>> listB = listA >>> listA ['A', 'B', 'C', 'D'] >>> listB ['A', 'B', 'C', 'D'] >>> listA.remove('C') >>> listA ['A', 'B', 'D'] >>> listB ['A', 'B', 'D']
As you can see, B was assigned to reference the same list as A and removing something from A also removed it from B.
At times that is fine, however, sometimes you need a clone of the list so that changes in A do not reflect in B. A very simple way to accomplish that is by using slicing. Our example now becomes:
>>> listA = ['A', 'B', 'C', 'D'] >>> listB = listA[:] >>> listA ['A', 'B', 'C', 'D'] >>> listB ['A', 'B', 'C', 'D'] >>> listA.remove('C') >>> listA ['A', 'B', 'D'] >>> listB ['A', 'B', 'C', 'D']
There we go, problem solved.
Posted in 
content rss
