liveBook · Manning

Copy

As explained in Get Programming: Learn to code with Python

Copying is the creation of a distinct object by transferring the elements or state of an original object.

Copying makes a new object with the same elements as the original. Unlike an alias, which points to the same object, a copy can be changed without changing the original. section 28.0 section 28.2

For lists, you can make a copy in several ways:

  • Create a new list from an existing one with list(original). section 28.2
  • Call original.copy() to create a separate list with the same elements. section 28.2
  • Use sorted(original) to get a sorted list while leaving the original unchanged. section 28.2
artists = ["monet", "picasso"]
painters = artists.copy()
painters.append("van gogh")

painters
Out[24]: ["monet", "picasso", "van gogh"]

artists
Out[25]: ["monet", "picasso"]

Appending to painters changes the copied list, while artists stays unchanged. section 28.2

A copy is also useful when you need to iterate over one list while changing another. For example, a stack can return a copy of its internal list so callers cannot mutate that stored list through the returned value. section 28.2 section 32.1

How Get Programming: Learn to code with Python covers it

How deep it goes
Demonstrates list(), copy(), and sorted() with concrete results, and contrasts copies with aliases.
Examples
Uses artist lists, sorted ages, list filtering, and a stack method that returns copied elements.
What you can do after
Apply Python's list(), copy(), and sorted() to create separate or sorted lists without changing the original.
How it connects
Connects copying to mutable objects, aliases, sorted lists, iteration, and encapsulating a stack's internal list.

Also explained in

Compare how 5 books explain copy →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Get Programming: Learn to code with Python. The section links point to the parts of the book it draws on.