Difference between shallow copy and deep copy
It means that any changes made to a copy of the object do not reflect in the original object. In python, this is implemented using “deepcopy()” function. whereas in shallow copy any changes made to a copy of an object do reflect in the original object. In python, this is implemented using the “copy()” function.
Example 1: Using copy()
Unlike copy(), the assignment operator does deep copy.
Python3
# Python program to demonstrate difference # between = and copy() original = { 1 : 'geeks' , 2 : 'for' } # copying using copy() function new = original.copy() # removing all elements from new list # and printing both new.clear() print ( 'new: ' , new) print ( 'original: ' , original) original = { 1 : 'one' , 2 : 'two' } # copying using = new = original # removing all elements from new list # and printing both new.clear() print ( 'new: ' , new) print ( 'original: ' , original) |
Output:
new: {} original: {1: 'geeks', 2: 'for'} new: {} original: {}
Example 2: Using copy.deepcopy
Unlike deepcopy(), the assignment operator does deep copy.
Python3
import copy # Python program to demonstrate difference # between = and copy() original = { 1 : 'geeks' , 2 : 'for' } # copying using copy() function new = copy.deepcopy(original) # removing all elements from new list # and printing both new.clear() print ( 'new: ' , new) print ( 'original: ' , original) original = { 1 : 'one' , 2 : 'two' } # copying using = new = original # removing all elements from new list # and printing both new.clear() print ( 'new: ' , new) print ( 'original: ' , original) |
Output:
new: {} original: {1: 'geeks', 2: 'for'} new: {} original: {}
Python Dictionary copy()
Python Dictionary copy() method returns a shallow copy of the dictionary. let’s see the Python Dictionary copy() method with examples:
Examples
Input: original = {1:'geeks', 2:'for'} new = original.copy() // Operation Output: original: {1: 'one', 2: 'two'} new: {1: 'one', 2: 'two'}