How do you copy an object in Python?

By Rama, 7 months ago
  • Bookmark
0

What is Shallow Copy and deep copy?

Copy
Python
1 Answer
0

To copy object in python use copy module.

There are two ways of creating copies for the given object using the copy module


1.Shallow Copy :

It 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.


2.Deep Copy :

It copies all values recursively from source to target object, i.e. it even duplicates the objects referenced by the source object.


Example :


from copy import copy, deepcopy

list_1 = [10, 20, [x, y], 50, 60, 70]

## shallow copy

list_2 = copy(list_1) 
list_2[5] = 99
list_2[2].append(z)

list_1     # output => [10, 20, ['x', 'y', 'z'], 50, 60, 99]
list_2     # output => [10, 20, ['x', 'y', 'z'], 50, 60, 99]

## deep copy

list_3 = deepcopy(list_1)
list_3[3] = 35
list_3[2].append('@')

list_3    # output => [10, 20, ['x', 'y', 'z', '@'], 35, 60, 70]
list_1    # output => [10, 20, ['x', 'y', 'z'], 50, 60, 70]

Your Answer

Webinars

Live Masterclass on "Python for Artificial Intelligence"

Dec 4th (7:00 PM) 195 Registered
More webinars

Related Discussions

Running random forest algorithm with one variable

View More