Paul's Python CoursePPC

Shallow and deep copies

Not met yet

copy(), list(...), dict(...) and [:] make a shallow copy: a new outer list or dictionary, holding references to the same inner ones. copy.deepcopy() copies everything inside too, all the way down. For flat data a shallow copy is enough; for data inside data, copy deeply or build it fresh.

Try it

main.py

Output

Press Run and what your program prints shows up here.

Easy to get wrong

  • Thinks copy() also copies the lists and dictionaries inside, so the copy shares nothing.
  • Thinks deepcopy() still shares the inner lists and dictionaries with the original.
  • Thinks list[:] gives another label on the same list rather than a new list.

Where it comes up