Question:medium

Consider the given Python program.
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, []))
Which of the following is the correct output of this program?

Show Hint

A mutable default argument like \(lst=[]\) is created once at function definition and reused across calls that do not pass their own list.
Updated On: Jul 22, 2026
  • [1]
    [2]
    [3]
  • [1]
    [1, 2]
    [3]
  • [1]
    [2]
    [1, 2, 3]
  • [1]
    [1, 2]
    [1, 3]
Show Solution

The Correct Option is B

Solution and Explanation

This is the classic Python "mutable default argument" gotcha, and the cleanest way to solve it is to track exactly one thing: which list object each call is actually appending to, the shared default, or a fresh one passed in explicitly.

Python evaluates $lst=[]$ exactly once, when the function is defined, not once per call. That single list object then lives on as long as the function exists, and any call that skips the second argument automatically falls back to reusing that same object, carrying forward whatever was appended to it in earlier calls.

  1. print(append_to_lst(1)): no second argument given, so this call uses the shared default list, which is empty at this point. Appending 1 changes the shared list from $[]$ to $[1]$, and $[1]$ is printed. From now on, the shared default object itself is $[1]$, not empty.
  2. print(append_to_lst(2)): again no second argument, so Python reaches for the very same shared list, but that list is no longer empty, it already holds $[1]$ from step 1. Appending 2 makes it $[1, 2]$, and that is what prints.
  3. print(append_to_lst(3, [])): this time an explicit empty list $[]$ is passed in. This is a completely different, brand new list object, unrelated to the shared default one. Appending 3 to this fresh list gives $[3]$, which prints. The shared default list quietly stays at $[1, 2]$ behind the scenes, but this call never touches it.

Stacking the three printed results in order: $[1]$, then $[1, 2]$, then $[3]$. That sequence corresponds to option (B).

A quick way to remember this for future code review: never use a mutable object like a list or dict as a default argument value unless you actually want it shared and remembered across calls, use $None$ as the default and create a fresh list inside the function body instead.

\[ \boxed{[1],\ [1,2],\ [3]} \]
Was this answer helpful?
0