Question 30: Understanding Mutable Arguments in Python Functions

Mutable Arguments in Python

Click Here for a Similar Question

Contents

This question tests your understanding of Python’s handling of mutable default arguments in functions.

When a function has a mutable default parameter (such as a list or dictionary), the same object is reused across multiple function calls unless a new argument is explicitly passed.

This can lead to unexpected behaviors if the default argument is modified.

Can you predict the output when a function with a mutable default list argument is called multiple times, both with and without overriding the default?

This problem is ideal for exploring scoping, function defaults, and Python’s handling of mutable objects.

Mutable Arguments in Python Mutable Arguments in Python Mutable Arguments in Python

Question

What will be the output of the following code?

def add_to_list(val, my_list=[]):
    my_list.append(val)
    return my_list

list1 = add_to_list(1)
list2 = add_to_list(2, [])
list3 = add_to_list(3)

print(list1)
print(list2)
print(list3)














Answer: A

This tricky question revolves around the concept of mutable default arguments in Python.

  1. add_to_list(1):
    • Since no my_list is provided, Python uses the default list [].
    • The function appends 1 to this default list, making my_list = [1].
    • The returned value, list1, is [1].
  2. add_to_list(2, []):
    • Here, we provide a new, empty list [] for my_list.
    • This list is a separate instance, so the function appends 2 to it, resulting in [2].
    • The returned value, list2, is [2].
  3. add_to_list(3):
    • Since my_list is not provided, Python reuses the original default list (from the first call).
    • This list is now [1] from the first call.
    • The function appends 3 to this list, making it [1, 3].
    • The returned value, list3, is [1, 3].

Thus:

  • list1 and list3 both reference the same default list, which ends up as [1, 3].
  • list2 is a separate list, containing only [2].

Leave a Reply