Interview Question

What is shallow copy?

A shallow copy duplicates the outer object but shares nested objects.

💡 Concept ✅ Quick Revision 🐍 Python

Answer

A shallow copy creates a new outer container but reuses references to nested objects. • copy.copy() performs a shallow copy. • Many containers also provide their own shallow-copy operations. • Changing a shared nested mutable object is visible through both containers.

💡 Simple Example

import copy original = [[1], [2]] cloned = copy.copy(original) cloned[0].append(9) print(original)

Output

[[1, 9], [2]]

⚡ Quick Revision

A shallow copy duplicates the outer object but shares nested objects.