Copy Module in Python

From this tutorial, you will be learning about Python Copy module. It has a short learning curve when compared to other modules especially if you have read other topics.

Note: The syntax used in the below section is for Python 3. You may change it to use with a different version of Python.

Copy Module in Python

Must Read – 9 Ways to Copy a File in Python

What is Copy Module?

Copy Module is a set of functions that are related to copying different elements of a list, objects, arrays, etc. It can be used to create shallow copies as well as deep copies.

The difference between shallow and deep copy operations got explained in a tutorial on Deep Copy vs. Shallow Copy in Python 3.

How does the Copy module work?

The syntax to implement Copy Module is as shown below

import copy
copy.submodule_name(arguments)

To perform the shallow copy, you can use the following code:

import copy
copy.copy(object_name)

For the deep copy, follow the below approach:

import copy
copy.deepcopy(object_name)

In the next section, a few programs are implemented to demonstrate the Copy Module in Python 3.

Program Examples

Create the shallow copy of a list:

Here is a simple program to demonstrate the Shallow Copy.

import copy

a = [ [1, 2, 3], [4, 5, 6] ]
b = copy.copy(a)

print(a)
print(b)

a[1][2] = 23
b[0][0] = 98

print(a)
print(b)

The output will come as:

Python Shallow Copy

Create a deep copy of a list:

Check another program for Deep Copy operation.

import copy

a = [ [1, 2, 3], [4, 5, 6] ]
b = copy.deepcopy(a)

print(a)
print(b)

a[1][2] = 23
b[0][0] = 98

print(a)
print(b)

The output will come as:

Python Deep Copy

Best,

TechBeamers