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?
originalList[:]does create a new copy oforiginalList. But it doesn't create new copies of the lists insideoriginalList. - PM 2RingoriginalList, but not of the three lists contained in it (i.e., a shallow copy). Also see:copy.deepcopy()- Lukas Grafswapby using tuple assignment:node[0][0], node[0][1] = node[1][0], node[0][0]. - PM 2Ring