Last active
October 25, 2020 08:21
-
-
Save karpanGit/2ddf174d0b91221c9bf7046de864f645 to your computer and use it in GitHub Desktop.
shallow vs deep copies in python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# copy lists in python | |
a = [1, 2, [3],[[4]]] | |
print('a'.ljust(20, ' '),id(a), id(a[2]), id(a[2][0]), id(a[3][0])) | |
# not a copy | |
b = a | |
print('b (not a copy)'.ljust(20, ' '), id(b), id(b[2]), id(b[2][0]), id(b[3][0])) | |
# a shallow copy I | |
b = a[:] | |
print('b (shallow copy I)'.ljust(20, ' '), id(b), id(b[2]), id(b[2][0]), id(b[3][0])) | |
# a shallow copy II | |
b = list(a) | |
print('b (shallow copy II)'.ljust(20, ' '), id(b), id(b[2]), id(b[2][0]), id(b[3][0])) | |
# a shallow copy III | |
b = a.copy() | |
print('b (shallow copy III)'.ljust(20, ' '), id(b), id(b[2]), id(b[2][0]), id(b[3][0])) | |
# a shallow copy IV | |
from copy import copy | |
b = copy(a) | |
print('b (shallow copy IV)'.ljust(20, ' '), id(b), id(b[2]), id(b[2][0]), id(b[3][0])) | |
# a deep copy | |
from copy import deepcopy | |
b = deepcopy(a) | |
print('b (deep copy)'.ljust(20, ' '), id(b), id(b[2]), id(b[2][0]), id(b[3][0])) | |
# This returns | |
# a 2609788978112 2609788977728 140725089937248 2609788979520 | |
# b (not a copy) 2609788978112 2609788977728 140725089937248 2609788979520 | |
# b (shallow copy I) 2610139993984 2609788977728 140725089937248 2609788979520 | |
# b (shallow copy II) 2609788977216 2609788977728 140725089937248 2609788979520 | |
# b (shallow copy III) 2610139999616 2609788977728 140725089937248 2609788979520 | |
# b (shallow copy IV) 2610139827328 2609788977728 140725089937248 2609788979520 | |
# b (deep copy) 2610139993984 2609788977216 140725089937248 2609788846272 | |
# Slicing in python always creates shallow copies. This is proven by the code | |
data = [1, 2, [3,33,333] ,4, 5] | |
s = slice(0, 3, 2) | |
data2 = data[s] | |
print('data2 (prior to modification)', data2) | |
data2[0] = -2000 | |
data2[1][0] = -3000 | |
print('data2 (after modification)', data2) | |
print('data (after modification)', data) | |
# that returns | |
# data2 (prior to modification) [1, [3, 33, 333]] | |
# data2 (after modification) [-2000, [-3000, 33, 333]] | |
# data (after modification) [1, 2, [-3000, 33, 333], 4, 5] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
With deep copy the address of an immutable object remains the same. However, the address of the mutable container of the immutable object changes which means that a new assignment will not change the original.