1

I have a multidimensional list in Python 3.9 which contains several Strings. Now I want [["a", "b"], ["c", "d"]] to be [["d", "a"], ["b", "c"]]. So every String move up one place. Here is the code I have tried:

list = [["a", "b"], ["c", "d"]]
helper = list
list[0][0] = helper[1][1]
list[0][1] = helper[0][0]
list[1][0] = helper[0][1]
list[1][1] = helper[1][0]
print(list)

But unfortunately, the code gives me [['d', 'd'], ['d', 'd']] instead of [["d", "a"], ["b", "c"]]. Printing out helper at the end of my program gives me [['d', 'd'], ['d', 'd']] as well, but why? Shouldn't the helper be [["a", "b"], ["c", "d"]] because I set him to list at the top of my program.

list = [["a", "b"], ["c", "d"]]
helper = list

However, the following code proves that helper is changing during my program:
list = [["a", "b"], ["c", "d"]]
helper = list
print("Top of program:", helper)
list[0][0] = helper[1][1]
list[0][1] = helper[0][0]
list[1][0] = helper[0][1]
list[1][1] = helper[1][0]
print("Bottom of program:", helper)

Output:

Top of program: [['a', 'b'], ['c', 'd']]
Bottom of program: [['d', 'd'], ['d', 'd']]

So my question is why helper changes its values and why my program doesn't do what it should do.

Michael Brown
  • 137
  • 2
  • 13
  • Does this answer your question? [List of lists changes reflected across sublists unexpectedly](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly) – Nick Dec 23 '20 at 07:33
  • `helper` is a *reference* to `list`, so any changes to `list` change `helper` as well. – Nick Dec 23 '20 at 07:34
  • 3
    Initialize `helper` as a deep copy of list: `helper = [sub[:] for sub in list]` – user2390182 Dec 23 '20 at 07:36
  • thanks, that solved my problem. When you put your answer as a "real" answer I can mark it as "accepted" – Michael Brown Dec 23 '20 at 08:19
  • Also I would discourage you from using list as name for your list, as it is already a predefined function, that will be overwritten by your definition – NationBoneless Dec 23 '20 at 20:25

0 Answers0