Interview Prep/Python for DevOps/Language essentials & functions

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.

All Python for DevOps questions Roadmap: Python for automation

More on Language essentials & functions