0% found this document useful (0 votes)
19 views

Pythonquestion 16

To copy an object in Python, the copy module must be used as assignment does not copy but binds names. There are two types of copies - shallow copies copy the object structure but not nested objects, while deep copies recursively copy all nested objects as well. The copy and deepcopy functions perform shallow and deep copies respectively.

Uploaded by

ameetamarwadi
Copyright
© © All Rights Reserved
Available Formats
Download as ODT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Pythonquestion 16

To copy an object in Python, the copy module must be used as assignment does not copy but binds names. There are two types of copies - shallow copies copy the object structure but not nested objects, while deep copies recursively copy all nested objects as well. The copy and deepcopy functions perform shallow and deep copies respectively.

Uploaded by

ameetamarwadi
Copyright
© © All Rights Reserved
Available Formats
Download as ODT, PDF, TXT or read online on Scribd
You are on page 1/ 1

How do you copy an object in Python?

In Python, the assignment statement (= operator) does not copy objects. Instead, it creates a
binding between the existing object and the target variable name. To create copies of an
object in Python, we need to use the copy module. Moreover, there are two ways of creating
copies for the given object using the copy module -
• Shallow Copy is a bit-wise copy of an object. The copied object created has an exact copy of
the values in the original object. If either of the values are references to other objects, just the
reference addresses for the same are copied.
• Deep Copy copies all values recursively from source to target object, i.e. it even duplicates
the objects referenced by the source object.
from copy import copy, deepcopy

list_1 = [1, 2, [3, 5], 4]

## shallow copy

list_2 = copy(list_1)
list_2[3] = 7
list_2[2].append(6)

list_2 # output => [1, 2, [3, 5, 6], 7]


list_1 # output => [1, 2, [3, 5, 6], 4]

## deep copy

list_3 = deepcopy(list_1)
list_3[3] = 8
list_3[2].append(7)

list_3 # output => [1, 2, [3, 5, 6, 7], 8]


list_1 # output => [1, 2, [3, 5, 6], 4]

You might also like