Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Original list gets modified in python [duplicate]

Tags:

python

I have a simple code as below:

def swap(node):
    m00         = node[0][0]
    node[0][0]  = node[1][0]
    node[0][1]  = m00

originalList = [[1,2,3], [4,5,6], [7,8,9]]

# temp = list(originalList)
temp = originalList[:]

swap(temp)

print originalList

Initially I define a list with the values shown above and then copy this list to a temporary one. I have tried both methods of copying. Then I perform a swap function using temp list and print the original list again. As a result the original list is changed. What's the reason behind this behavior?

like image 610
user3764893 Avatar asked Nov 26 '25 21:11

user3764893


1 Answers

The way you are copying the list (both ways) is known as a shallow copy. This can be better seen this way:

l1 = [1,2,3]
l2 = [4,5,6]
l3 = [7,8,9]
originalList = [l1,l2,l3]
temp = originalList[:]
l1[0] = 0

>>> temp
[[0, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> originalList
[[0, 2, 3], [4, 5, 6], [7, 8, 9]]

When you make a shallow copy of originalList, you are still getting references to l1, l2, and l3. Any changes you make to those smaller lists will be reflected in both originalList and any shallow copies you make. You want a deep copy operation. For your purposes, Scott Hunter's answer of

temp = [x[:] for x in originalList]

will work. In the general case, the method deepcopy from the copy module should get you a deep copy of whatever objects you need. It is still likely better to use in this case as it is a few orders of magnitude faster.

like image 82
Brien Avatar answered Nov 29 '25 10:11

Brien



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!