Paul's Python CoursePPC

The mutable default trap

Not met yet

A default value is made once, when Python runs the def line, not on every call. If the default is a list or dictionary and the function changes it, every later call sees the changes. Default to None and make a new list inside the function instead.

Try it

main.py

Output

Press Run and what your program prints shows up here.

Easy to get wrong

  • Thinks a default list or dictionary is made fresh on every call, rather than once when the def line runs.
  • Thinks the None-then-new-list pattern still shares one list between calls.

Where it comes up