Skip to content
Artwork for Data Science Tech Brief By HackerNoon
Data Science Tech Brief By HackerNoon · Today · 8 min

How Shallow and Deep Copies Work in Python

This story was originally published on HackerNoon at: https://hackernoon.com/how-shallow-and-deep-copies-work-in-python. I copied a Python dictionary, but the original still changed. Here's how shallow copies, shared references, and deep copies actually work. Check more stories related to data-science at: https://hackernoon.com/c/data-science. You can also check exclusive content about #python-programming, #python-dictionaries, #shallow-copy, #deep-copy, #python-mutability, #object-references, #python-debugging, #mutable-default-arguments, and more. This story was written by: @sohelalam79. Learn more about this writer by checking @sohelalam79's about page, and for more stories, please visit hackernoon.com. `dict.copy()` only copies the outer dictionary nested lists/dicts stay shared, so mutating them changes both copies. It's not a bug, it's shallow copy working as designed. Use `deepcopy()` only when you need full independence.

0:00-8:31

transcript

No transcript — this publisher did not publish one.

show notes

This story was originally published on HackerNoon at: https://hackernoon.com/how-shallow-and-deep-copies-work-in-python.
I copied a Python dictionary, but the original still changed. Here's how shallow copies, shared references, and deep copies actually work.
Check more stories related to data-science at: https://hackernoon.com/c/data-science. You can also check exclusive content about #python-programming, #python-dictionaries, #shallow-copy, #deep-copy, #python-mutability, #object-references, #python-debugging, #mutable-default-arguments, and more.

This story was written by: @sohelalam79. Learn more about this writer by checking @sohelalam79's about page, and for more stories, please visit hackernoon.com.

`dict.copy()` only copies the outer dictionary nested lists/dicts stay shared, so mutating them changes both copies. It's not a bug, it's shallow copy working as designed. Use `deepcopy()` only when you need full independence.

links13