I've just started to learn Python for a school project but I'm a bit confused with the pointers. Which is weird because I just aced my Assembly exam.
So in this case:
var1 = [0, 1]
var2 = [2, 3]
matrix = [
newVars = [[0, 1], [2, 3]]
var1 = newVars[:]
var2 = newVars[:]
var1[:] = newVars[:]
var2[:] = newVars[:]
Python is pass by reference. This means that when you do:
matrix = [ var1, var2, var2, var1 ]
And you change
var2, it changes the values in the matrix. The matrix has pointers to
var2, and it is not possible to have pure values in python. Instead, you can use
list.copy() to get a new copy of the variable.
newVars, on the other hand, is completely unrelated to the other values shown. But when you assign
var2 a new value, it is now unrelated to the original matrix. (You changed where it points to, but not the pointer's value itself, so the matrix retains the original value)
A list slicing creates a new object. But since the matrix has pointers to the original object, and
var2 simply changed what they point to, the matrix does not change. It's like this:
var1 & var2: create a new list and assign its pointer to your self var1 -> 0x0001 var2 -> 0x0002 matrix: take pointers from var1 and var2 and store it in you. matrix -> 0x0001, 0x0002. newVars: create a new list and assign its pointer to your self newVars -> 0x0004 newVars: create a new list and assign its pointer into your current list (2x) newVars -> 0x0004: 0x0005, 0x0006 var1 & var2: switch your pointer to a new *copy* of a slice of newVars I have made. (creates new pointers) var1 -> 0x0007 var2 -> 0x0008 matrix -> 0x0001, 0x0002.
0x0001 changes everything that has a pointer to it, changing a pointer changes
0x0001, but slicing a list creates a new list.