0

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]]
Ch3steR
  • 20,090
  • 4
  • 28
  • 58
newbie5
  • 45
  • 4

1 Answers1

1

Sometimes a copy is not enough, and you need a deep copy:

import copy
new_list = copy.deepcopy(old_list)

The rest of your code should be the same

Juan C
  • 5,846
  • 2
  • 17
  • 51
  • So it's a duplicate and you should vote to close; see [How to Answer](https://stackoverflow.com/help/how-to-answer) - *Not all questions can or should be answered here. Save yourself some frustration and avoid trying to answer questions which... ...have already been asked and answered many times before.* – kaya3 Mar 11 '20 at 19:14