Collections
Copying Collections
Assignment does not copy a collection. It gives the same list another name.
Source
rows = [["Ada"], ["Grace"]]
alias = rows
print(alias is rows)Output
TrueA shallow copy creates a new outer list, but nested lists are still shared.
Source
shallow = rows.copy()
rows[0].append("Lovelace")
print(shallow is rows)
print(rows[0] is shallow[0])
print(shallow)Output
False
True
[['Ada', 'Lovelace'], ['Grace']]A deep copy is independent at the nested level, so later mutation of rows[0] does not appear in deep.
Source
import copy
rows = [["Ada"], ["Grace"]]
deep = copy.deepcopy(rows)
rows[0].append("Lovelace")
print(rows[0] is deep[0])
print(deep)Output
False
[['Ada'], ['Grace']]Notes
- Assignment aliases; it does not copy.
- Shallow copies duplicate the outer container only.
- Deep copies are useful for nested independence, but they can be expensive and surprising for objects with external resources.
See also
- prerequisite: Mutability
- related: Lists
- related: Dictionaries
Run the complete example
Expected output
True
False
True
False
[['Ada', 'Lovelace'], ['Grace']]
[['Ada'], ['Grace']]
Execution time appears here after you run the example.