Copying in Python
Copying Using Assignment Operator
An assignment statement in python do not create copies of an object. Instead they only point to the object in memory, such that changes in one copy will be reflected in the other. This is also known as
#Python Aliasing.
Python Aliasing
In Python programming, when the value of one variable is assigned to another variable, aliasing occurs in which reference is copied rather than copying the actual value. But may be fine when using on immutable objects. When copying mutable objects, want to create real copies of the object.
fvar = <value>
#aliasing
svar = fvar
Example:
first_variable = "PYTHON"
print("Value of first:", first_variable)
print("Reference of first:", id(first_variable))
print("--------------")
second_variable = first_variable # making an alias
print("Value of second:", second_variable)
print("Reference of second:", id(second_variable))
Output:
Value of first: PYTHON
Reference of first: 4480676656
--------------
Value of second: PYTHON
Reference of second: 4480676656
Notice how both variables have the same reference id in memory.
A reference is a name that refers to the specific location in memory of a value (object).
Deep vs Shallow Copy
A shallow copy means constructing a new object and then populating it with references to the child objects found in the original; i.e., does not create copies of the child objects themselves. Instead, this only returns a view of the original object.
xs = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
ys = list(xs)
A deep copy makes the copying process recursive. This means that python first constructs a new collection object and then recursively populating it with copies of the child objects found in the original; this produces a fully independent clone of the original object and all of its children.
Deep copies of python objects can be done by using the copy module in the Python standard library:
import copy
In the copy module there is a method called deepcopy() that will take care of the operation for you:
lst = [1, 2, 3, 4]
new_lst = copy.deepcopy(lst)