Collections

Copying Collections

Copies can duplicate the outer container while nested objects may still be shared.

Assignment does not copy a collection. It gives the same list another name.

Source

rows = [["Ada"], ["Grace"]]
alias = rows

print(alias is rows)

Output

True
BEFOREfirstsecond["python"]AFTER APPENDfirstsecond["python","workers"]
Without copy() two names share the same object; mutating through one is visible through the other.

A 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

See also

Run the complete example

Example code

Expected output

True
False
True
False
[['Ada', 'Lovelace'], ['Grace']]
[['Ada'], ['Grace']]

Execution time appears here after you run the example.