Copying an object in Python(‘=’ vs ‘copy’ Module)

Apoorve
Apoorve
Jun 4, 2020 · 3 min read

Python has always held the upper hand when it comes to code readability, and productivity. With vast library support for simple maths operation to that for machine learning projects, it makes it even easier to build an application, in no time.

Python is not so forgiving in nature. If you are working on a deployment level software, you just can’t afford messing up with it. Try writing a for loop without using indentation. (☉。☉)!

for i in range(0,10):
print(i)
#error
File “<stdin>”, line 2
print(i)
^
IndentationError: expected an indented block

You just can’t expect more or less! But, its not always that you come across an error while executing your code. That is what I am going to explain using =(Assignment Operator) and copy module in Python.No matter, if you haven’t used them before. I will explain it to depth!

Following topics will be covered in this blog:

  1. Assignment operator over objects(list, here).
  2. copy Module : Shallow Copy and Deep Copy

1. Assignment operator over objects

“=” or Assignment operator is often used in every programming language while assigning a variable some value.

#declaring variables
var_a = 5
var_b = 6
#print sum
print(var_a+ var_b) #11

Though it works fine in general, but that’s not the case, while assigning a list to a variable. To explain it in brevity, here is an example of how it works.

.append() is a method used with list . It takes a single argument as input — item. The item can be numbers, dictionaries, another list and so on. It doesn’t return any value, i.e. it returns None.

Assignment statements in Python do not copy objects, they create bindings between a target and an object. It simply sets a reference of list_1 to new_list. and doesn’t actually copy all the elements of the original list. Therefore, each time we make some changes to new_list, it will modify the original list_1 and vice-versa.

No error! But still, something is wrong! XD
No error! But still, something is wrong! XD

What if you are working with a live database, trying copying the content(actually setting up a reference using ‘=’) to some new variable. Then you simply appended some secret keys to this content and clients get to see that(since the original content has been modified too)! Gotcha! You ended up making a typo, you can’t afford to redo!

This is not what we actually gonna do, but that needs to be solved! Well! Python has an in-build modulecopy in order to encounter it.

2. copy Module

The copy module allows us to actually create an immutable (or partially mutable) copy of an object. This is performed with the Shallow and deep copy operations.

Shallow Copy and Deep Copy

.deepcopy(list) is used to create immutable objects(here list). That is, any changes in the new object do not affect the original object. In both Case I and Case II, appending [6,7] to li_new, and altering li_new[1](second element in the list), does not reflect the changes to li.

We sometimes need mutable copy, and here is when Shallow Copy comes into play.

Here, .copy(list) does not affect the original list in Case I and III. But in Case II, 3(li[1][1]) is replaced by [8,9,10]. This is because,unlike deep copy, shallow copy(.copy()) does reflect changes to the original object, while dealing with compound objects( objects containing another object (like lists, dictionaries, etc.)) such as

[1, [2 ,3 , 4], 5, 6]                #list in list
[1, {'first': 2, 'second': 3}, 4, 5] #dictionary in list

Voila! We now have a clear implication on dealing with objects while copying and altering data, contained within it.

So the next time you are working with the live database, prevent yourself from this Onosecond!👇🏼 or refer this blog! :)

The worst ONOSECOND

The Startup

Get smarter at building your thing. Join The Startup’s +787K followers.

Sign up for Top 10 Stories

By The Startup

Get smarter at building your thing. Subscribe to receive The Startup's top 10 most read stories — delivered straight into your inbox, once a week. Take a look.

By signing up, you will create a Medium account if you don’t already have one. Review our Privacy Policy for more information about our privacy practices.

Check your inbox
Medium sent you an email at to complete your subscription.

Apoorve

Written by

Apoorve

Sophomore🎓 || ⭕pen Source Contributor 👨‍💻 || {{Pythonic🐍}} || Space Science🔭 || @Devscript @TesseractCoding @L-ByDo

The Startup

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +787K followers.

Apoorve

Written by

Apoorve

Sophomore🎓 || ⭕pen Source Contributor 👨‍💻 || {{Pythonic🐍}} || Space Science🔭 || @Devscript @TesseractCoding @L-ByDo

The Startup

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +787K followers.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

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