I have 2 lists:
list1 = [[1,2,3],[4,5,6],[7,8,9]]
list2 = list1.copy()
Then I want to swap elements in list_2 using function swap_elements(). I tried to swap numbers 1 and 9:
def swap_elements(old_list,x1,y1,x2,y2):
new_list = old_list.copy()
num1 = new_list[x1][y1]
num2 = new_list[x2][y2]
new_list[x1][y1] = num2
new_list[x2][y2] = num1
return new_list
list2 = swap_elements(list1,0,0,2,2)
after printing both lists, we can see that the elements in list_1 swapped too. Why?
print(list1)
print(list2)
gives output:
[[9, 2, 3], [4, 5, 6], [7, 8, 1]]
[[9, 2, 3], [4, 5, 6], [7, 8, 1]]