ProgrammingHardProduct-company MCQ pattern

What is printed?

What is printed?
def f(a, b={"x": 1}):
    b["x"] += a
    return b
print(f(1))
print(f(2))
  1. A. {'x': 2} {'x': 3}
  2. B. {'x': 2} {'x': 4}
  3. C. {'x': 1} {'x': 2}
  4. D. {'x': 3} {'x': 3}

Correct answer: B. {'x': 2} {'x': 4}

The default dict b is created once and shared across calls. f(1) adds 1 to x (1->2). f(2) then adds 2 to that SAME dict's now-current value (2->4).

More Python Programming questions

Exams that ask this topic