Python: Copy Nested List, Shallow/Deep Copy

By Xah Lee. Date: . Last updated: .

What is Shallow Copy?

All the following do shallow copy:

# example of shallow copy. Changing a nested item changes the original

xx = [[1, 2], 3]
yy = list(xx)

# modify xx
xx[0][1] = 9

# all true
print(xx == [[1, 9], 3])
print(yy == [[1, 9], 3])
print(xx == yy)

See also: Python: dict={} vs dict.clear() .

Copying Nested List, Deep Copy

Use the module “copy” to make a truely independent copy of a list.

import copy

xx = [[3, 4], 5]
yy = copy.deepcopy(xx)

xx[0][0] = 9

print(xx == [[9, 4], 5])

print(yy == [[3, 4], 5])

Copying List by Reference (Shallow Copy)

If you do this listA = listB, that'll copy a reference. That means: modifying one list also modifies the other.

xx = [3, 4, 5]
yy = xx
xx[0] = 7
print(yy == [7, 4, 5])

Check Equality of 2 Objects

You can check by using the “id” function. The id(obj) returns the object's memory address.

aa = [3, 4, 5]
bb = aa

print(id(aa))
# 4477411144

print(id(aa) == id(bb))
# True

Copy Flat List Using List Slice

You can make a copy by listB = listA[:]. When the first index are omitted, it default to 0. When the ending index is omitted, it default to length of the list.

xx = [3, 4, 5]
yy = xx[:]

print((id(xx) == id(yy)) == False)
print(xx == yy)

# all True

Copy Flat List Using .extend()

xx = [3, 4, 5]
yy = []
yy.extend(xx)

print((id(xx) == id(yy)) == False)
print(xx == yy)
# all True

Copy Flat List Using list()

The best way to copy flat list is

listB = list(listA)

xx = [3, 4, 5]
yy = list(xx)

print((id(xx) == id(yy)) == False)
print(xx == yy)
# all True

Python Data Structure