Sobes.tech
Junior — Middle

How are arguments passed to a function – by reference or by value?

sobes.tech AI

Answer from AI

In Python, arguments are passed to functions by object reference, but the behavior is similar to pass-by-value for immutable types.

This is called "pass-by-object-reference" or "pass-by-value of the reference".

  • If a mutable object (e.g., list, dictionary) is passed and its contents are modified inside the function, the changes will be visible outside.
  • If a new value is assigned to the parameter inside the function, it does not affect the object outside.

Example:

def func(x):
    x.append(4)  # Modify the object

def func2(x):
    x = [1, 2, 3]  # Assign a new object locally

lst = [1, 2, 3]
func(lst)
print(lst)  # Will output [1, 2, 3, 4]

func2(lst)
print(lst)  # Will output [1, 2, 3, 4], because assignment does not change the external object

Thus, in Python, there is no pass-by-reference in the classical sense, but objects are passed by reference, and mutable objects can be modified inside functions.