Sobes.tech
Junior

How are variables passed in Python: by reference or by value?

sobes.tech AI

Answer from AI

In Python, variables are passed by reference to objects. The value of a variable is essentially a reference to an object in memory.

When we assign one variable to another, we create a new reference to the same object. Changes to a mutable object through one reference will be visible through another.

Example with a mutable object (list):

# Create a list
list1 = [1, 2, 3]
# Assign list2 as a reference to the same list
list2 = list1
# Modify the list through list1
list1.append(4)
# Changes are visible through list2
# list2 now is [1, 2, 3, 4]
print(list2)

If we reassign a variable, it will start referencing a new object.

Example with reassignment:

# Reassign list1 to a new list
list1 = [5, 6]
# list2 still references the old list
# list2 remains [1, 2, 3, 4]
print(list2)

For immutable objects (strings, numbers, tuples), changing the variable's value always results in creating a new object and reassigning the reference. This creates the impression of pass-by-value, although it is still pass-by-reference to a new object.

Example with an immutable object (number):

# Create a number
num1 = 10
# Assign num2 as a reference to the same number
num2 = num1
# "Change" num1 (actually a new object 20 is created and num1 references it)
num1 = 20
# num2 still references the old object 10
# num2 remains 10
print(num2)

Thus, Python uses a "pass-by-object-reference" model, which behaves like pass-by-reference with mutable objects, and like pass-by-value with immutable objects—due to the creation of new objects during "changes."

How are variables passed in Python: by reference or… - sobes.tech