r/CodingHelp • u/[deleted] • Nov 09 '21
[Python] Why does this happen? How do I change a single entry?
4
u/PunkyMunky64 Nov 09 '21
Yep. The lists are linked together, which is an obvious problem for most advanced Python programmers. But I would have made the same mistake — this feature makes no sense in Python, no other type does this!
1
Nov 09 '21
It's weird because [0]*2 works just as [0,0] but it is different if instead of a 0 you have a list, for some reason (?)
1
u/kayden_polaris Nov 09 '21
When you use the multiplication operator with a array and a integer like
[0]*4, the result is a array where the content is repeated x times, so with the previous example, the result is[0, 0, 0, 0].Your expression is
[[0]*4]*4, when the parsing and evaluation of the expression is done, the interior multiplication is done first, to obtain[[0, 0, 0, 0, 0]]*4, which is a array that contains a array of 4 zeros. Finally the external multiplication is evaluated and repeats 4 times the reference of the internal array, which all reference the same array of four zeros.So if you have
[0]*2, the0inside the array is repeated twice, so the result is[0, 0], with both the internal0being integer values. If the expression was[[0]]*2, the result would be[[0], [0]]with both the internal[0]referencing the same instance of a array.
0
22
u/cndvcndv Nov 09 '21
When you run
listOfLists = [myList]*4listOfLists variable consists of elements all of which point to the same list. So when you change an element of myList, then the change appears in all elements of listOfLists variable.
You might want to read about mutability and list.copy() method.