All sample questions / Python

Python Scope, Functions and Closures, what does print(a, c) print after def build(value, acc=[])?

Block 2, Scope, Functions and Closures, question 11 of the Python sample

def build(value, acc=[]):
    acc.append(value)
    return acc
a = build(1)
b = build(2, [])
c = build(3)
print(a, c)

What does this print?

  1. A. [1, 3] [1, 3]
  2. B. [1, 2, 3] [1, 2, 3]
  3. C. [1] [3]
  4. D. [1, 3] [3]
Show the answer and why each option is right or wrong

Answer, A. [1, 3] [1, 3]

A. [1, 3] [1, 3]
Correct. Calls a and c both omit acc and therefore share the single default list, ending up with 1 and 3 appended to the same object, while b explicitly passes its own fresh empty list that is never touched by the others.
B. [1, 2, 3] [1, 2, 3]
Assumes the explicit empty list passed for b is the same shared default object, so its append also lands in the shared list.
C. [1] [3]
Assumes every call to build, including the one that omits acc, receives its own separate empty list.
D. [1, 3] [3]
Assumes a and c end up pointing at different list objects even though both calls used the same default argument.

Only calls that fall back to the default argument share the single object created at definition time. A call that explicitly passes its own list, like build(2, []), receives a brand new object that is completely independent of the shared default, so it never mixes with the values accumulated through the default.

The answer above is what the CPython interpreter printed when the snippet was run, not what someone expected it to do.

This question comes from a bank of 600 Python interview questions, all built the same way, sold as one PDF with the full answer key.

Get the 600 Python questions, 9 euros

Or SQL, Python, pandas and NumPy together, 1,636 questions, 19 euros

Or play the free Python sample, twenty questions in the browser, also as a free PDF.

Previous question Next question

Did this save you a lookup? Buy me a coffee on Ko-fi.