World's Best AI Learning Platform with profoundly Demanding Certification Programs
Designed by IITians, only for AI Learners.
Designed by IITians, only for AI Learners.
New to InsideAIML? Create an account
Employer? Create an account
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]