World's Best AI Learning Platform with profoundly Demanding Certification Programs
Designed by IITian's, only for AI Learners.
What is Shallow Copy and deep copy?
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.
from copy import copy, deepcopy list_1 = [10, 20, [x, y], 50, 60, 70] ## shallow copy list_2 = copy(list_1) list_2 = 99 list_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 = 35 list_3.append('@') list_3 # output => [10, 20, ['x', 'y', 'z', '@'], 35, 60, 70] list_1 # output => [10, 20, ['x', 'y', 'z'], 50, 60, 70]
Chat now for any query