0
Why is the argument of my function being changed?
https://code.sololearn.com/chaso5I32DL3/#py So the idea of this code is to take a list with this format: [["a", "b", "c"], ["d", "e", "f"], ["g", "h", "i"]] and change it into [["i", "h", "g"], ["f", "e", "d"], ["c", "b", "a"]] with newcluster[i][j] = cluster[j][i] why does it change the original cluster?
4 Respostas
+ 5
If the transformation logic is as simple as reversing the sublists order and also reversing the content of the sublists, then you can do this even without deepcopy, by using list comprehension.
newcluster = [sublist[::-1] for sublist in cluster[::-1]]
+ 4
a = b in Python only sticks a new name onto an object. Your list - just one list - now has two names.
You need to actually make a copy from that list.
In order to do that easily for now, you can use the deepcopy function from the copy module.
First lines of your code would look like this:
from copy import deepcopy
def game(cluster):
newcluster = deepcopy(cluster)
+ 3
because they're both pointing to the same memory address
+ 3
I'd personally also use comprehension, but that seems to be a bit confusing for people in the beginning.