Beyond doubt one of the most common operations that occurs in computer programs
is the copying of data.
An original artist is unable to copy. So he has only to copy in order to be original.
Jean Cocteau
Look deep into nature, and then you will understand everything better.
Albert Einstein
Either you decide to stay in the shallow end of the pool or you go out in the ocean.
Christopher Reeve
Supported by:Linux and Python Courses and Seminars

Shallow and Deep Copy

Introduction

As we have seen in the chapter "Data Types and Variables", Python has a strange behaviour
- in comparison with other programming languages -
when assigning and copying simple data types like integers and strings. The difference between
shallow and deep copying is only relevant for compound objects, which are objects containing other
objects, like lists or class instances.

In the following code snippet y points to the same memory location than X. This changes,
when we assign a different value to y. In this case y will receive a separate memory location,
as we have seen in the chapter "Data Types and Variables".

>>> x = 3
>>> y = x

But even if this internal behaviour appears strange compared to programming languages like C,
C++ and Perl, yet the observable results of the assignments answer our expectations.
But it can be problematic, if we copy mutable objects like lists and dictionaries.

Python creates real copies only if it has to, i.e. if the user, the programmer, explicitly
demands it.

We will introduce you to the most crucial problems, which can occur when copying mutable objects, i.e.
when copying lists and dictionaries.

Copying a list

In the example above a simple list is assigned to colours1. In the next step we assign colour1
to colours2. After this, a new list is assigned to colours2.

As we have expected, the values of colours1 remained unchanged. Like it was in our example
in the chapter "Data types and variables", a new memory location had been allocated for colours2,
because we have assigned a complete new list to this variable.

But the question is, what will happen, if we change an element of the list of colours2 or colours1?
In the example above, we assign a new value to the second element of colours2.
Lots of beginners will be astonished that the list of colours1 has been "automatically"
changed as well.
The explanation is that there has been no new assignment to colours2, only to one of its elements.

Copy with the Slice Operator

It's possible to completely copy shallow list structures with the slice operator without having any
of the side effects, which we have described above: