How Shallow and Deep Copies Work in Python

https://hackernoon.imgix.net/images/4bfpoAFKgXWLIX7Z9FTXYpFW4XR2-6r037oo.png

A few weeks ago I was testing a small feature nothing fancy, just duplicating a dictionary before running an update, the way you're taught to "be safe." I only touched the copy. And somehow, the original changed too. I hadn't touched it. I hadn't reassigned it. It just changed.

It wasn't a Python bug. It was something I'd been getting wrong without realizing it: a variable doesn't hold an object it holds a reference to one. Once that clicked, this entire category of "silent" bugs stopped feeling random.

What You Expect

original = {"name": "Sohel", "skills": ["Python", "JS"]}copy_dict = original.copy()copy_dict["skills"].append("React")print(original["skills"])

You'd expect this to print:

['Python', 'JS']

You made a copy. You only modified the copy. The original should be untouched, right?

What Actually Happens

['Python', 'JS', 'React']

The original dictionary changed even though you never touched original directly. You only touched copy_dict.

First, There's Not Always a Copy at...

Copyright of this story solely belongs to hackernoon.com. To see the full text click HERE

Read more