liveBook · Manning

Copy

As explained in The Quick Python Book, Fourth Edition

Copying is the creation of a separate representation of an existing value, object, or data, preserving some or all of its contents or state.

A copy gives you another way to work with a value or container, but it may not be independent of the original. For mutable containers, the key distinction is between a shallow copy, which shares nested objects, and a deep copy, which copies them too. section 5.6

Choose a copying method based on the contents:

  • For a list, a full slice such as x[:] makes a shallow copy; x + [] and x * 1 do too. section 5.6
  • For a dictionary, use x.copy() for a shallow copy. Use copy.deepcopy(x) when nested mutable values should be independent. section 7.2
  • For a tuple, these copy-like methods produce an alias, not a new object; the tuple itself cannot be modified. section 5.7.1

Nested lists

With original = [[0], 1], shallow = original[:] leaves both lists sharing the inner list: changing shallow[0][0] also changes original[0][0]. By contrast, deep = copy.deepcopy(original) keeps nested lists independent. section 5.6

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Works through shallow and deep copy behavior with nested values, but does not cover copying internals.
Examples
Demonstrates nested-list mutations, list slicing, deepcopy, dictionary copy(), and tuple aliases.
What you can do after
Apply Python slicing, copy(), or copy.deepcopy() to choose the intended degree of independence.
How it connects
Connects copying to lists, dictionaries, tuples, mutability, object references, and the copy module.

Also explained in

Compare how 5 books explain copy →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.