What does assignment do in Python, and how do shallow and deep copies differ?
BeginnerConceptLanguage essentials & functions
Answer
Assignment never copies; it binds a name to an existing object. b = a makes both names point at the same list.
- Shallow copy (
a.copy(),list(a),dict(a),copy.copy(a)) creates a new outer container but shares the nested objects. - Deep copy (
copy.deepcopy(a)) recursively copies everything.
import copy
base = {"tags": {"env": "dev"}}
shallow = base.copy()
shallow["tags"]["env"] = "prod" # also changes base!
deep = copy.deepcopy(base)
We hit this when we build per-environment configs from a shared template dict.
More on Language essentials & functions
Why is Python the default scripting language in so many DevOps teams, and where would you not use it?BeginnerWhat is the difference between mutable and immutable types? Give examples.BeginnerExplain the mutable default argument bug and how to fix it.IntermediateWhat is the difference between `==` and `is`?BeginnerWhat values are "falsy" in Python, and why does it matter in scripts?BeginnerWhen do you choose a list, tuple, set or dict?Beginner