Programming · Flashcard

f(v, acc=[]) appends v to acc. What does f(2) return after f(1)?

  • A[1, 2] — the default list is created once, at def time
  • B[2] — a fresh default list is built for every single call
  • C[1, 2] — but only while the calls share one thread
  • DA TypeError — a mutable default is rejected at def time

Why this is the answer

Default values are evaluated once, when the def statement runs, and stored on the function object — so both calls append to the same list and f(2) returns [1, 2]. A fresh list per call is the common wrong mental model; the fix is acc=None plus acc = [] in the body. Threads play no part, and Python accepts mutable defaults without complaint.

Official docs
Study in Gnoseed →