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 still effect the original list

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

xx[0][1] = 9

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

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.

listA = [3, 4, 5]
listB = listA
listA[0] = 7
print(listB)
# [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.

listA = [3, 4, 5]
listB = listA[:]

print(id(listA) == id(listB))
# False

print(listA == listB)
# True

Copy Flat List Using .extend()

listA = [3, 4, 5]
listB = []
listB.extend(listA)

print(id(listA) == id(listB))
# False

print(listA == listB)
# True

Copy Flat List Using list()

The best way to copy flat list is

listB = list(listA)

listA = [3, 4, 5]
listB = list(listA)

print(id(listA) == id(listB))
# False

print(listA == listB)
# True

Python Data Structure

Python

Overview

Help

Comment

String

Arithmetic

Boolean

Conditional

Loop

Data Structure

Function and Class

Module

Misc

Regex

Text Processing

Web

Misc