Nergal Nergal - 2 months ago 5
Python Question

How variables work in Python?

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 = [
var1, var2,
var2, var1
]

newVars = [[0, 1], [2, 3]]


If I do this:

var1 = newVars[2][:]
var2 = newVars[1][:]


The matrix gonna keep the same values as it was before. Because the vars now located to a new address, but the values of the matrix are not.

But obviously if I do this:

var1[:] = newVars[2][:]
var2[:] = newVars[1][:]


It's gonna change the stored value at the specific memory location.

My questions are the following:


  • Am I right with my conclusion?

  • Is there any other way I can change the values in the matrix by changing my variables?

  • Is there anything else I had to know about the vars in Python?


Answer

Python is pass by reference. This means that when you do:

matrix = [
    var1, var2,
    var2, var1
]

And you change var1 or var2, it changes the values in the matrix. The matrix has pointers to var1 and 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 var1 or 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 var1 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.

Changing 0x0001 changes everything that has a pointer to it, changing a pointer changes 0x0001, but slicing a list creates a new list.