Why is the argument of my function being changed? | Sololearn: Learn to code for FREE!
Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula grƔtis
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?

9th Feb 2020, 6:37 PM
proxophy
proxophy - avatar
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]]
9th Feb 2020, 7:22 PM
Tibor Santa
Tibor Santa - avatar
+ 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)
9th Feb 2020, 7:14 PM
HonFu
HonFu - avatar
+ 3
because they're both pointing to the same memory address
9th Feb 2020, 6:39 PM
āœ³AsterisKāœ³
āœ³AsterisKāœ³ - avatar
+ 3
I'd personally also use comprehension, but that seems to be a bit confusing for people in the beginning.
9th Feb 2020, 7:24 PM
HonFu
HonFu - avatar