Analysis of Variables in Python

Assignment

In python, variables are just strings that refer to certain objects, which means that they are actually "pointers" in C/C++. When assigning a value to a variable, we actually modifies the reference of the variable:

1
2
3
a = 10
print(id(10)) # id(ob) return the address of ob
print(id(a))

The outputs are:

1
2
140723224699976
140723224699976

This shows that when creating a in python, it will bind a to the address of 10:

1

Fig. 1. Relationship between a and 10

Similarly, when changing the value of a, we are actually make a refer to the new value. In addition, when assigning the value of a to a new variable b, python does not assign new memory, but just make b refer to the value of a:

1
2
3
4
5
6
7
a = 10
b = a
a = 20
print(id(10))
print(id(b))
print(id(20))
print(id(a))

The outputs are:

1
2
3
4
140722523399240
140722523399240
140722523399560
140722523399560

2

Fig. 2. Reference of a and b

Parameters passing and return

The process of parameters passing is actually a process of assignment. Therefore, what we are passing to the formal parameter a is the reference of actual parameter b.

1
2
3
4
5
6
7
def func(a):
print(id(a))

b = 10
print(id(10))
print(id(b))
func(b)

The outputs are:

1
2
3
140723839624264
140723839624264
140723839624264

Similarly, when returning a value, we are also returning its reference:

1
2
3
4
5
6
def func():
a = 2
print(id(a))
return a
b = 2
print(id(b))

The outputs are:

1
2
140723839624008
140723839624008

Mutable & immutable objects

In python, everything is an object.

For variables that refer to immutable objects (e.g. string, number, tuple), we can't change the value of objects. When we change the value of variable, we are actually make the variable refer to another object (e.g. fig. 2).

For variables that refer to mutable objects (e.g. list, dictionary), they actually refer to the beginning address of their inner objects, which means variables are "secondary pointers". Therefore, we can change the value of the elements of these objects. Change the value of a variable will also make the variable refer to another object.

1
2
3
4
5
6
7
8
9
10
11
a = [1, 2]
b = a
b[0] += 1

print(a)
print(b)
print(id(a))
print(id(b))

a = [1]
print(id(a))

The outputs are:

1
2
3
4
5
[2, 2]
[2, 2]
1330208790976
1330208790976
1330210492608

For mutable objects, their member functions may have side effects while member functions of immutable objects will not have side effects but return a new object. The class defined by users is always mutable obejct.

Reference