What will be printed by the following Python code snippet?

def func(val, lst=[]):
lst.append(val)
return lst

print(func(1))
print(func(2))

Answer and explanation

Correct answer: A. [1] then [1, 2]

  1. Step 1: In Python, default parameter arguments are evaluated once when the function definition is executed, not at each call.
  2. Step 2: The mutable default list `lst` persists across invocations. The first call appends 1 (`[1]`), and the second call appends 2 to the same list instance (`[1, 2]`).
Answer
[1] then [1, 2].
Why not the others: `[1]` then `[2]` assumes a new list is created on each call; `[1, 2]` then `[1, 2]` misidentifies the first return value.

Practise more Algorithms and Python Programming.

Free questions with an explanation for every one, and full timed EmSAT Achieve (UAE) mock tests.

What will be printed by the following… | EmSAT Achieve (UAE)