Ad space (banner)
🐍Python Lessons
Lesson 41 / 69

Shallow Copy vs. Deep Copy

This lesson covers the difference between shallow and deep copies, so you can avoid unexpected bugs when duplicating lists and dictionaries. It's written for anyone searching "Python shallow copy deep copy" or "Python copy deepcopy".

A shallow copy duplicates only the outermost container, while any nested objects inside remain shared with the original. A deep copy duplicates everything all the way down, so changing the copy never affects the original. .copy() makes a shallow copy; copy.deepcopy() makes a deep copy.

The sample code shallow-copies a dictionary, original, into shallow with .copy(), and you can see that modifying the nested part (address["city"]) also changes the original original. In contrast, modifying a deep copy made with copy.deepcopy(original) has no effect on the original data.

"I made a copy, but somehow the original changed too" is a classic beginner bug that happens exactly because this distinction isn't understood. This difference matters most when working with data that has "containers inside containers," like nested lists or dictionaries.

In real development, correctly choosing the right kind of copy matters, for example, when temporarily editing form input while wanting to preserve the original data. Applications that manage a lot of state especially need to understand this distinction.

Python
OUTPUT

💡 The Python engine may take a few seconds to load the first time you run code.

Ad space (banner)
Ad space (in-article)