Hackforge Academy

Category: python

Copying Nested Objects

Published on 27 Oct 2026

Explanation

A shallow copy creates a new outer object but shares nested objects. A deep copy recursively copies nested objects where supported.

Code:

import copy
original = [[1, 2], [3, 4]]
shallow = copy.copy(original)
deep = copy.deepcopy(original)
print(original[0] is shallow[0], original[0] is deep[0])

Explanation

A shallow copy of a flat list creates a separate outer list.

Code:

import copy
original = [10, 20]
clone = copy.copy(original)
clone.append(30)
print(original, clone)

Explanation

Nested mutable objects remain shared after a shallow copy, so mutations to them are visible through both structures.

Code:

import copy
original = [[1, 2]]
clone = copy.copy(original)
clone[0].append(99)
print(original)

Explanation

deepcopy() recursively copies nested structures, though deep copying can require additional time and memory.

Code:

import copy
original = {'skills': ['Python']}
clone = copy.deepcopy(original)
clone['skills'].append('SQL')
print(original, clone)

Explanation

Use shallow copy when shared nested objects are acceptable; use deep copy when nested mutable state must be independent.

Code:

import copy
config = {'flags': {'debug': False}}
shallow = copy.copy(config)
deep = copy.deepcopy(config)
shallow['flags']['debug'] = True
print(config, deep)

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community