Deep vs shallow copy

There is two types of copying objects in Python: deep and shallow. Here I will show how to perform both of them using built-in module copy.

Import module copy in your code

import copy

Try shallow copy

a = [4]b = copy.copy(a)
>>> b
[4]
>>> id(a)
140122699353672
>>> id(b)
140122699353864

Let’s see how it works on deeply nested lists

>>> a = [[1], [2], [3]]
>>> b = copy.copy(a)
>>> a.append([6])
>>> a
[[1], [2], [3], [6]]
>>> b
[[1], [2], [3]]
>>> a[2][0] = 4
>>> a
[[1], [2], [4], [6]]
>>> b
[[1], [2], [4]]

Change of element a[2][0] leading to change in corresponding element b[2][0] as all nested lists in a are passed as reference on default.

Now let’s try deep copying:

>>> b = copy.deepcopy(a)
>>> a
[[1], [2], [4], [6]]
>>> b
[[1], [2], [4], [6]]
>>> a[2][0] = 8
>>> a
[[1], [2], [8], [6]]
>>> b
[[1], [2], [4], [6]]
>>>

We can see that when changing element with index [2][0] in a corresponding element in b is not changing as all nested lists in a are copied to b (nor passed by reference).

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Top 5 Additions and Modifications That Can Make Your Manufacturing Plant More Efficient

UNDERSTANDING GIT

Subscribe Cloud Pub/Sub Topic in Kubernetes Operator

The S.O.L.I.D principles for a solid software

Help RecWorks build a thriving environment to teach novice software developers about skills in the…

Canada Trusts Volthread!

Fibonacci Series

Sending AWS Cloudwatch Alarms to Amazon Chime

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Privalov Vladimir

Privalov Vladimir

More from Medium

Increasing Triplet Subsequence

Learning From Redis #4 / Reference Counting

You Autocomplete Me

A primer on Recursive algorithms