Question:

def append_to_lst(val, lst=[]):
lst.append(val)
return lst
print(append_to_lst(1))
print(append_to_lst(2))
print(append_to_lst(3, []))

Show Hint

Using mutable default arguments is a common "gotcha" in Python. The recommended practice is to use `None` as a default value and then create a new list or dictionary inside the function if the argument is `None`. For example: `def func(lst=None): if lst is None: lst = [] ...`. This ensures a new mutable object is created for each call.
Updated On: Feb 23, 2026
  • [1] [1,2] [3]
  • [1] [1,2] [1,3]
  • [1] [2] [1,2,3]
  • [1] [2] [3]
Hide Solution
collegedunia
Verified By Collegedunia

The Correct Option is A

Solution and Explanation

Step 1: Understanding the Question:
The question tests understanding of a specific feature in Python: mutable default arguments in function definitions.
Step 2: Key Concept - Mutable Default Arguments:
In Python, default arguments for functions are evaluated only once, when the function is defined, not each time the function is called. If a default argument is a mutable object (like a list or a dictionary), this single object will be shared across all calls to the function that do not explicitly provide a value for that argument.
Step 3: Tracing the Code Execution:
  • Function Definition: When the line \texttt{def append_to_lst(val, lst=[]):} is executed, Python creates a single, empty list object in memory. This object is set as the permanent default value for the \texttt{lst} parameter. Let's refer to this list as \texttt{L_default}.
  • First Call: \texttt{print(append_to_lst(1))}
    This call does not provide a second argument, so the default list \texttt{L_default} is used for the parameter \texttt{lst}.
    The code \texttt{L_default.append(1)} is executed, so \texttt{L_default} now contains \texttt{[1]}.
    The function returns \texttt{L_default}.
    Output: \texttt{[1]}.
  • Second Call: \texttt{print(append_to_lst(2))}
    Again, no second argument is provided, so the {same} default list \texttt{L_default} is used.
    The code \texttt{L_default.append(2)} is executed, and \texttt{L_default} is modified to become \texttt{[1, 2]}.
    The function returns the updated \texttt{L_default}.
    Output: \texttt{[1, 2]}.
  • Third Call: \texttt{print(append_to_lst(3, []))}
    This time, a second argument is explicitly provided: a new, empty list \texttt{[]}.
    The default list \texttt{L_default} is NOT used. The \texttt{lst} parameter is bound to this new list for this specific call.
    The code \texttt{[].append(3)} is executed, and the new list becomes \texttt{[3]}.
    This call does not affect \texttt{L_default} in any way.
    Output: \texttt{[3]}.
Step 4: Final Answer:
The sequence of outputs will be \texttt{[1]}, then \texttt{[1, 2]}, and finally \texttt{[3]}. This matches option (A).
Was this answer helpful?
0
0

Questions Asked in GATE DA exam

View More Questions