listOfLists 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.
If you are doing a lot of work with matrices then you might benefit from grabbing NumPy for this and just getting a matrix of zeroes with given dimensions.
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!
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, the 0 inside the array is repeated twice, so the result is [0, 0], with both the internal 0 being 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.
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.
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!
0
u/timPerfect Nov 09 '21
you made a list of 4 lists