AI InterviewSearch…Search problems, topics, or pages…Ctrl KGet started
Hardpythonfunctionsmutability

~105s

A default argument that remembers

What does this Python program print?

def add(item, target=[]):
    target.append(item)
    return target

print(add(1))
print(add(2))
Show the answer and the worked solution

Correct answer: B.

[1] and then [1, 2]

Worked solution

  1. The default [] is evaluated once, when the def statement runs, and stored with the function.
  2. The first call appends 1 to that stored list and returns it, printing [1].
  3. The second call receives the very same list, which already holds 1, appends 2 and prints [1, 2], so the two lines are [1] and then [1, 2].

Answer: [1] and then [1, 2].

The idea

Default arguments are evaluated once at definition time, so a mutable default is shared across every call. The standard remedy is target=None with target = [] inside the body.

Shortcut. Each print runs straight after its call, so the first line is [1] and the second must contain 2, which leaves two options; both calls share one stored default list, so it is [1, 2].

Common trap. "[1] and then [2]" assumes a fresh empty list on every call, which is true only for defaults created inside the body.

A default argument that remembers — Aptitude Question

A default argument that remembers: What does this Python program print? Answer and worked solution on CodeKairo.

Question

What does this Python program print?

def add(item, target=[]):
    target.append(item)
    return target

print(add(1))
print(add(2))

Options

  1. [1] and then [2]
  2. [1] and then [1, 2]
  3. [1] and then [1]
  4. [1, 2] and then [1, 2]
Show the answer and the worked solution

Correct answer: B. [1] and then [1, 2]

Worked solution

  1. The default [] is evaluated once, when the def statement runs, and stored with the function.
  2. The first call appends 1 to that stored list and returns it, printing [1].
  3. The second call receives the very same list, which already holds 1, appends 2 and prints [1, 2], so the two lines are [1] and then [1, 2].

Answer: [1] and then [1, 2].

The idea

Default arguments are evaluated once at definition time, so a mutable default is shared across every call. The standard remedy is target=None with target = [] inside the body.

Shortcut. Each print runs straight after its call, so the first line is [1] and the second must contain 2, which leaves two options; both calls share one stored default list, so it is [1, 2].

Common trap. "[1] and then [2]" assumes a fresh empty list on every call, which is true only for defaults created inside the body.

All Programming Fundamentals questions · placement mock tests