Posts

Showing posts with the label python list copy

Copy Compound object lists using deepcopy

Sometimes you might get into trouble while copying a compound object list to another in Python. If this is so, then you should use the copy module of Python. To know details about shallow and deep copy operations in Python please visit http://docs.python.org/lib/module-copy.html To copy simple lists without using copy module of python, you can use the method described in another post of my blog http://love-python.blogspot.com/2008/04/how-to-copy-list-in-python.html One of my friend found that this method wasn't working for him while copying a graph into another (he used adjacency matrix to represent graph), then he tried deepcopy and got rid of the problem.

How to copy a list in Python?

Let me tell about a common mistake many python beginners do while trying to copy a list to another list. Suppose to copy a list listA to listB, they use listB = listA , now if you change something in one list, the other list is changed automatically as they refer to same list - actually listB points to listA! So the proper way should be listB = [] listB.extend(listA) Here I paste some experiments I made: >>> listA = [1, 2, 3, 4, 5] >>> listB = listA >>> listC = [] >>> listC.extend(listA) >>> listB [1, 2, 3, 4, 5] >>> listC [1, 2, 3, 4, 5] >>> listA [1, 2, 3, 4, 5] >>> listB[4] = 0 >>> listB [1, 2, 3, 4, 0] >>> listA [1, 2, 3, 4, 0] >>> listC [1, 2, 3, 4, 5] >>> listC[4] = 10 >>> listC [1, 2, 3, 4, 10] >>> listA [1, 2, 3, 4, 0] >>> listB [1, 2, 3, 4, 0] >>> Hope you get the point!