Sobes.tech
Junior — Middle

How do mutable objects change when passed as arguments to a function?

sobes.tech AI

Answer from AI

In Python, objects of mutable types (such as lists, dictionaries, sets) are passed to functions by reference to the object. This means that if you modify the contents of the object inside the function (for example, adding an element to a list), these changes will be visible outside the function.

Example:

def add_element(lst):
    lst.append(10)

my_list = [1, 2, 3]
add_element(my_list)
print(my_list)  # Outputs: [1, 2, 3, 10]

However, if you assign a new object to the parameter inside the function, it does not affect the external object:

def replace_list(lst):
    lst = [4, 5, 6]  # Creates a new object, local to the function

my_list = [1, 2, 3]
replace_list(my_list)
print(my_list)  # Outputs: [1, 2, 3]

Thus, when passing mutable objects to a function, you can modify their contents, and these changes will persist outside the function.