Python copy Module — ELI5
Imagine you and your friend share a Google Doc. If your friend deletes a paragraph, it’s gone for you too — because you’re both looking at the same document.
Now imagine you download a copy to your computer. You can edit your version all day, and your friend’s version stays untouched. That’s an independent copy.
Python works like Google Docs by default. When you do new_list = old_list, both names point to the same list in memory. Change one, and the other changes too. This catches people off guard all the time.
The copy module gives you two tools to make real, independent copies:
-
copy.copy()— makes a shallow copy. It creates a new container but the items inside still point to the original objects. Like photocopying a folder — the folder is new, but the papers inside are the same ones. -
copy.deepcopy()— makes a deep copy. Everything gets duplicated, all the way down. Like printing entirely new copies of every paper inside the folder too.
When does this matter?
Whenever you have lists, dictionaries, or objects that contain other lists or objects — and you want to modify one version without affecting the other.
One thing to remember
= in Python shares data, it doesn’t copy it. Use copy.copy() for a quick surface-level duplicate, and copy.deepcopy() when you need a fully independent clone.
See Also
- Python Atexit How Python's atexit module lets your program clean up after itself right before it shuts down.
- Python Bisect Sorted Lists How Python's bisect module finds things in sorted lists the way you'd find a word in a dictionary — by jumping to the middle.
- Python Contextlib How Python's contextlib module makes the 'with' statement work for anything, not just files.
- Python Dataclass Field Metadata How Python dataclass fields can carry hidden notes — like sticky notes on a filing cabinet that tools read automatically.
- Python Datetime Handling Why dealing with dates and times in Python is trickier than it sounds — and how the datetime module tames the chaos