Copying nested data

Lesson 8 of 20 · Functional Python: values, behavior, and choices

A new outer container can still share its contents with the original. A shallow copy duplicates the outer container, not the nested objects.

original = {"tags": ["dry"], "active": True}
shallow = original.copy()
shallow["tags"].append("warm")
print(original["tags"])
['dry', 'warm']

Both dictionaries refer to the same tags list. To change that list independently, copy it too:

def add_tag(record, tag):
    updated = record.copy()
    updated["tags"] = record["tags"] + [tag]
    return updated

first = {"tags": ["dry"], "active": True}
second = add_tag(first, "warm")
print(first["tags"])
print(second["tags"])
['dry']
['dry', 'warm']

The new dictionary and new tags list are distinct; other nested mutable values, if present, could still be shared. copy.deepcopy recursively copies many structures but can be expensive or unsuitable for some objects. Copy according to the ownership you need. Likewise, sorted(items) returns a new outer list whereas items.sort() mutates the existing list and returns None; elements may still be shared.

Chapter index