Sobes.tech
Middle

How do you understand the reference model on which Python is based?

sobes.tech AI

Answer from AI

In Python, variables are references (links) to objects in memory, not containers for the actual values. When we assign a value to a variable, it actually starts pointing to the object containing that value. When a variable referencing a mutable object (e.g., list or dictionary) is changed, the object itself is modified. When a variable referencing an immutable object (e.g., number, string, or tuple) is changed, a new object is created in memory, and the variable starts referencing it.

# Immutable object (int)
a = 10
b = a # a and b initially reference the same object
print(id(a), id(b)) # Same id

a = 20 # Creates a new object 20, a now references it
print(id(a), id(b)) # Different id, b still references 10

# Mutable object (list)
list1 = [1, 2, 3]
list2 = list1 # list1 and list2 reference the same list object
print(id(list1), id(list2)) # Same id

list1.append(4) # Modifies the object referenced by both
print(list1)
print(list2) # Both lists are modified
print(id(list1), id(list2)) # Still the same id

Reference counting mechanism is used for automatic memory management. Each object tracks the number of variables referencing it. When the reference count reaches zero, the object becomes inaccessible, and the garbage collector frees the memory it occupies.

An important difference from languages with direct value storage in variables (e.g., C): in Python, assigning b = a does not copy the value of a into b, but b starts referencing the same object that a references.