The GATE Grind

GATE 2026 DA – Question 16

Programming, Data Structures and Algorithms · Programming in Python · 1 mark · Multiple choice

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?

  1. Three lines: [1], then [2], then [3]
  2. Three lines: [1], then [1, 2], then [3]
  3. Three lines: [1], then [2], then [1, 2, 3]
  4. Three lines: [1], then [1, 2], then [1, 3]

Practise this question in The GATE Grind →

Show answer and explanation

Correct answer: (B) Three lines: [1], then [1, 2], then [3]

Explanation

A default argument is evaluated once, when the function is defined, so every call that does not pass a list shares the same default list. The first call appends 1 to it and prints [1]. The second call appends 2 to the same list and prints [1, 2]. The third call passes a new empty list, so it prints [3].