Sobes.tech
Junior — Middle

How are objects passed to Python functions — by value or by reference?

sobes.tech AI

Answer from AI

In Python, objects are passed to functions by reference, but the behavior is similar to passing by value for immutable types. This means that the function receives a reference to the object, and if the object is mutable (e.g., a list or dictionary), changes inside the function will be visible outside. If the object is immutable (e.g., a number, string, tuple), attempting to modify the object inside the function will result in creating a new object, and the original object will remain unchanged.

Example:

def modify_list(lst):
    lst.append(4)  # modify the object

def modify_int(x):
    x += 1  # create a new object

my_list = [1, 2, 3]
modify_list(my_list)
print(my_list)  # [1, 2, 3, 4]

my_int = 10
modify_int(my_int)
print(my_int)  # 10

Thus, it can be said that passing is by reference to the object, but the behavior depends on the mutability of the object.