Python 3 reference · List Methods
Python List copy() Method
Return a shallow copy of the list: a new list with the same items. Nested objects are still shared.
Python 3 Since 3.0
Syntax
list.copy()
Return value
A new list.
Examples
original = [1, 2, 3]
clone = original.copy()
clone.append(4)
print(original, clone)
Output
[1, 2, 3] [1, 2, 3, 4]
import copy
grid = [[0, 0], [0, 0]]
shallow = grid.copy()
shallow[0][0] = 9
print(grid) # the inner list is shared
deep = copy.deepcopy(grid)
deep[1][1] = 7
print(grid, deep)
Output
[[9, 0], [0, 0]] [[9, 0], [0, 0]] [[9, 0], [0, 7]]
items.copy(), items[:] and list(items) all make shallow copies. Use copy.deepcopy() for nested lists.
Version history
| Version | Change |
|---|---|
| Python 3.0 | Added |
Related
list()· Create a list: an ordered, changeable sequence. Called with an iterable, it copies its items into a new list.list.extend()· Add every item from an iterable to the end of the list, in place. Like append() for many items at once.- Python Lists · tutorial