Computer Science I / Functions and Parameter Passing
Practice question · Multiple choice

A function with a default argument def f(x, items=[]) behaves strangely: the list keeps its contents between calls. Why?

Hints
  1. Ask when the expression [] is actually evaluated: at definition, or at each call?
  2. Call the function three times with no argument. How many list objects exist?
Show the answer

A. Because the default is evaluated once at definition, not on each call

Why

One list is created at definition time and shared by every default-argument call, so appends accumulate across calls. The idiom is items=None with a check inside, and this trap is why mutable defaults are near the top of every Python gotchas list.

Read the lesson: Functions and Parameter Passing →

Practise Functions and Parameter Passing

The app has 5 more questions on this lesson, and keeps your place in the course. Computer Science I is free to start.

More questions on Functions and Parameter Passing