Question:

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
collegedunia
Verified By Collegedunia

The Correct Option is B

Solution and Explanation

Step 1: Understand the mutable default argument trap.
In Python, a default argument value like \(lst=[]\) is created only once, at the moment the function is defined, not fresh every time the function is called. If a call does not explicitly pass its own value for \(lst\), Python reuses that exact same list object from before, including any changes made to it by earlier calls. Only a call that explicitly supplies its own list, like \(append\_to\_lst(3, [])\), gets a brand new separate list instead of the shared one.

Step 2: Trace the first call.
\(append\_to\_lst(1)\) does not pass a value for \(lst\), so Python uses the shared default list, which starts as an empty list \([]\). Inside the function, \(1\) is appended, turning the shared list into \([1]\), and this \([1]\) is returned and printed. The shared default list itself is now permanently \([1]\) until it is mutated again.

Step 3: Trace the second call.
\(append\_to\_lst(2)\) again does not pass a value for \(lst\), so it uses that same shared list, which is currently \([1]\) from the previous call, not a fresh empty list. Appending \(2\) turns it into \([1, 2]\), and this \([1, 2]\) is what gets returned and printed.

Step 4: Trace the third call.
\(append\_to\_lst(3, [])\) explicitly passes a brand new, separate empty list as \(lst\). This new list has nothing to do with the shared default list from the earlier two calls. Appending \(3\) to this fresh list gives \([3]\), which is printed. The shared default list is untouched by this call and remains \([1, 2]\) internally, but that does not affect this printed output.

Step 5: Final Answer.
Putting the three printed lines together: \([1]\), then \([1, 2]\), then \([3]\). This matches option (B). \[ \boxed{[1] \;\; [1,2] \;\; [3]} \]
Was this answer helpful?
0
0

Top GATE DA Data Science and Artificial Intelligence Questions

View More Questions

Top GATE DA Programming in Python Questions

View More Questions