Python List Copies and Aliasing
Core idea
Assignment other = items binds a second name to the same list (an alias). Use items.copy() or items[:] to create a shallow copy: a new outer list containing references to the same items. Replacing an outer slot affects only that outer list, but modifying a shared nested list can affect both.
items = [1, 2]alias = itemsalias.append(3)print(items)print(alias is items)Both names refer to the same object; changing it through either name is visible through the other.
Separate outer lists
items = [1, 2]backup = items.copy()backup[0] = 9print(items)print(backup)The outer lists are independent; replacing a slot in backup does not replace the original slot.
Shared nested list
rows = [[1], [2]]backup = rows.copy()backup[0].append(9)print(rows)print(backup[0] is rows[0])The first nested list is shared even though the outer lists are distinct.
Common mistake
A shallow copy is not recursive. For a list of independent rows, you can build a new outer list and append a copy of each row. This only copies two levels, not arbitrary nesting.
Practice
Make a shallow copy of [[2], [4]]. First replace its first row entirely, then append to its second row. Predict what happens to the original after each change.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Copies and aliasing
Check your understanding of list copies and aliasing.
What is printed?
a = [1]b = ab.append(2)print(a)What is printed?
a = [1]b = a.copy()print(a is b)What is printed?
a = [[1]]b = a.copy()b[0].append(3)print(a)Which statement creates an alias instead of a copy?