Junior
How are arguments passed to a function: by reference or by value?
sobes.tech AI
Answer from AI
In Python, arguments are not passed exactly by reference nor exactly by value, but by a mechanism often called "pass by object reference" or "pass by sharing".
This means the following:
- When passing an argument to a function, a reference to the object is passed.
- If the object is mutable (e.g., list, dictionary), then changes inside the function will be visible outside it.
- If the object is immutable (e.g., number, string, tuple), then attempting to modify it inside the function will create a new object, and the original object outside the function will remain unchanged.
Mutable objects:
# Mutable object (list)
def modify_list(items):
items.append(4)
my_list = [1, 2, 3]
modify_list(my_list)
# my_list is now [1, 2, 3, 4]
Immutable objects:
# Immutable object (number)
def modify_number(num):
num = num + 1
my_number = 5
modify_number(my_number)
# my_number is still 5