Junior — Middle
How is an argument passed in Python functions and how does it affect the program's behavior?
sobes.tech AI
Answer from AI
In Python, arguments are passed by object reference, but the behavior depends on the mutability of the object:
- For immutable types (int, str, tuple), a new object is created when the argument is modified inside the function, and the original remains unchanged.
- For mutable types (list, dict, set), modifications inside the function affect the original object.
This means that if a mutable object is passed and modified inside the function, the changes will be visible outside. For immutable objects, modifications inside the function will not affect the external object.
Example:
def add_item(lst):
lst.append(4)
my_list = [1, 2, 3]
add_item(my_list)
print(my_list) # Outputs [1, 2, 3, 4]
def increment(n):
n += 1
num = 5
increment(num)
print(num) # Outputs 5