Shallow copy vs deep copy

  • Deep copy is related to nested structures. If you have list of lists, then deepcopy() copies the nested lists also, so it is a recursive copy.
  • With shallow copy, you have a new outer list, but inner lists are references. So, a shallow copy doesn't create a copy of nested objects, instead it just copies the reference of nested objects.
  • Shallow copy:
    • copy.copy()
    • list()
    • Slicing [:]
    • list.copy()
    • Comprehension
Shallow copy examples
import copy
a = [[1, 2], [3, 4]]
b = a.copy()          # or a[:], or list(a) — all SHALLOW
b[0].append(99)
a                     # [[1, 2, 99], [3, 4]] — inner lists still shared

c = copy.deepcopy(a)  # recursively copies; handles cycles
list_ = [[[0]*3]*3]*3
list_[0][0][0] = 1

print(list_) # 9 ones
# [1 0 0][1 0 0][1 0 0]
# [1 0 0][1 0 0][1 0 0]
# [1 0 0][1 0 0][1 0 0]
def foo(x):
	x = [3, 2, 1]
	
def bar(x):
	x[0] = "hello"
	
arr = [1, 2, 3]
foo(arr)
print(arr) # 1, 2, 3

bar(arr)
print(arr) # hello, 2, 3
SuperMade with Super