Quick Question About Variables

Hello, I have been trying to understand the referencing between variables. For example:

array = [number for number in range(5)]
test_variable = array[2]

Here in this code above, does test_variable referencing to the “array” list or is it just a another aboject ? I mean, if this code was written with classes, for example:

array = [hash_map() for i in range(5)]
test_variable = array[0]
test_variable.assing(key, 10)

Here in the code above, does the test_variable affect “array[0]” or is it just another instance of "array[0] ?

You can play around with the id() method that returns something like the address (where something is actually stored). In the following example I’m highlighting that when you set a variable equal to a value, you’re essentially creating a pointer of that variable to the value’s address. Note that id()'s have to be unique, you can’t have the same id for 5 and 6.

>>> test = 5
>>> variable = test
>>> variable
5
>>> test = 7
>>> variable # this would output 7 if it pointed to `test`, but it was set to point to `5` implicitly
5
>>> test
7
>>> test = 5
>>> id(test)
4376327424
>>> variable = test
>>> id(variable)
4376327424
>>> test = 7
>>> id(test)
4376327488
>>> variable
5
>>> id(variable)
4376327424
>>> id(5)
4376327424
>>> id(7)
4376327488

N.B.:
This is a bit of an oversimplification, it’s not quiiite a pure address (I’m adding this caveat for diff versions of python, so I don’t want to over-generalize), for more discussion on the topic, you can look at something like:

1 Like

For example, when you set “variable” to “test”( variable = test ), if you use a method on “variable”, does this method also affect “test” variable ?

Using a method will not affect either as you have to store somewhere. A quick check in the terminal can reveal some of its characteristics:

>>> test = 5
>>> variable = test
>>> pow(variable,2)
25
>>> variable
5
>>> variable = pow(variable,2)
>>> variable
25
>>> test
5
1 Like