🐍 Python Intermediate

What is Python's copy module?

Answer

The copy module provides object copying functions. copy.copy(obj) creates a shallow copy — a new object whose contents are references to the same objects as the original. For containers (lists, dicts), a new container is created but the elements inside are still the same objects. copy.deepcopy(obj) creates a deep copy — recursively copies all nested objects so the copy is completely independent. Deep copy handles circular references automatically using a memo dict. Custom copy behavior: implement __copy__(self) for shallow and __deepcopy__(self, memo) for deep copy. Performance: deep copy is significantly slower than shallow copy. Avoid deep-copying large structures unnecessarily. In practice: for immutable objects (int, str, tuple), copying is unnecessary since they cannot change. For mutable nested structures that you need to modify independently, use deep copy.