Understanding Shallow and Deep Copy in Python

Trending 2 months ago

Python offers respective businesslike approaches to managing data. Understanding shallow and heavy transcript concepts is important erstwhile moving pinch information structures for illustration nested lists, dictionaries, aliases civilization objects.

Both shallow and heavy transcript fto you make replicas of information structures, but they enactment otherwise regarding nested data.

Using Shallow Copy

Shallow transcript useful by creating a transcript of nan top-level building of nan original object. This intends that, if nan original entity contains nested objects, nan transcript will reference nan aforesaid nested objects that nan original does. In different words, making a shallow transcript of an entity duplicates its outermost structure, not immoderate nested objects it whitethorn contain.

To execute a shallow transcript successful Python, you tin usage nan transcript module's copy() usability aliases nan .copy() method connected nan object.

Consider an illustration of working pinch a database aliases dictionary successful Python.

import copy

main_list = [29, 49, ["Q", "R"]]
shallow_copy = copy.copy(main_list)


shallow_copy[2][0] = 99
main_list[2][1] = 100

print(f"The main list: {main_list}")
print(f"The shallow transcript list: {shallow_copy}")

In nan codification above, nan main_list adaptable holds a database containing integers and an soul database (nested object) containing letters. The transcript usability creates a transcript of nan main_list which nan codification stores successful different variable, shallow_copy.

Any changes you make to nan shallow_copy nested database will besides straight impact that of nan main_list and vice versa. These changes show that nan nested aliases soul database of nan shallow_copy is conscionable a reference to that of nan main_list, making nan changes use successful main_list too.

changes to nested database of shallow copy

Meanwhile, immoderate changes made to nan outer items (the integers) successful either shallow_copy aliases main_list will only impact that instance. These outer items are independent values successful their ain right, not conscionable specified references.

import copy

main_list = [29, 49, ["Q", "R"]]
shallow_copy = copy.copy(main_list)


shallow_copy[0] = "M"
main_list[1] = "N"

print(f"The main list: {main_list}")
print(f"The shallow transcript list: {shallow_copy}")

The output demonstrates that some list’s outer items are independent of each other:

changes to outer items of shallow copy

The aforesaid thought applies erstwhile moving pinch dictionaries.

dict1 = {'ten': 10, 'twenty': 20, 'double':{'thirty': 30, 'sixty': 60}}
dict2 = dict1.copy()


dict1['double']['thirty'] = 30.00
dict1['ten'] = 10.00

print(f"The main dictionary, {dict1}")
print(f"The shallow transcript dictionary, {dict2}")

Changes made to nan nested dictionary of dict1 impact some dict1 and dict2. At nan aforesaid time, changes to nan outer items of dict1 impact only it.

using shallow transcript pinch nested dictionary

Using Deep Copy

Instead of referencing nan nested objects of nan original copy, a heavy transcript makes an wholly abstracted transcript of nan original entity and its nested objects. Modifying nan heavy transcript will not impact nan original entity and vice versa; they are genuinely abstracted values.

To make a heavy transcript successful Python, usage nan deepcopy() usability of nan transcript module.

Consider an illustration of moving pinch a list.

import copy

main_list = [200, 300, ["I", "J"]]
deep_copy = copy.deepcopy(main_list)


deep_copy[2][0] = "K"
main_list[0] = 500

print(f"The main list: {main_list}")
print(f"The heavy transcript list: {deep_copy}")

Here, nan codification performs a heavy transcript of main_list, creating an independent transcript named deep_copy.

When you modify nan nested database aliases outer items successful nan deep_copy, your changes do not impact nan original list, and vice versa. This demonstrates that nan nested database aliases outer elements are not shared betwixt nan 2 copies.

using heavy transcript pinch nested list

Working With Custom Objects

You tin create a civilization entity by defining a Python class and creating an lawsuit of nan class.

Here's an illustration of creating a elemental entity from a Book class:

class Book:
    def __init__(self, title, authors, price):
        self.title = title
        self.authors = authors
        self.price = price

    def __str__(self):
        return f"Book(title='{self.title}', author='{self.authors}', \
price='{self.price}')"

Now, make some a shallow transcript and a heavy transcript of an lawsuit of this Book people utilizing nan copy module.

import copy


book1 = Book("How to MakeUseOf Shallow Copy", \
             ["Bobby Jack", "Princewill Inyang"], 1000)


book2 = copy.copy(book1)


book1.authors.append("Yuvraj Chandra")
book1.price = 50


print(book1)
print(book2)

As you tin see, nan shallow transcript (book2) is simply a caller object, but it references nan aforesaid soul entity (author list) arsenic nan original entity (book1). Hence, a alteration to nan original object’s authors affects some instances (book1 and book2), while a alteration to nan outer point (price) only affects nan original entity (book1).

using shallow transcript pinch civilization object

On nan different hand, making a heavy transcript creates an independent transcript of nan original object, including copies of each objects contained wrong it.


book1 = Book("Why MakeUseOf Deep Copy?", \
             ["Bobby Jack", "Yuvraj Chandra"], 5000)


book2 = copy.deepcopy(book1)


book1.authors.append("Princewill Inyang")
book1.price = 60


print(book1)
print(book2)

In this case, nan heavy transcript (book2) is simply a wholly independent object, and modifying nan original entity (book1) does not impact it.

using heavy transcript pinch civilization object

Uses for Shallow Copy and Deep Copy

It’s captious to understand heavy and shallow transcript truthful you tin prime nan due attack for manipulating data. Here are immoderate scenarios wherever each method is applicable:

  • Use a shallow transcript if you want to replicate a analyzable entity without generating caller instances of its nested objects. This attack is much representation businesslike and faster than heavy transcript because it doesn't copy nested objects.
  • Use a shallow transcript to create a snapshot of an object's authorities while still sharing immoderate underlying information betwixt nan original and copied objects.
  • Use a heavy transcript if you want to modify a replica of an entity without impacting nan original. This generates independent copies of nested objects, ensuring that immoderate changes to nan transcript do not use to nan original.
  • Deep transcript is captious erstwhile you request independent copies of nested information structures, chiefly erstwhile dealing pinch recursive aliases intricate entity hierarchies.

Performance and Considerations

Since shallow transcript doesn't make caller instances of nested objects, it typically runs faster and uses little representation than heavy copy. However, nan original and nan shallow transcript whitethorn person unwanted broadside effects from changing shared soul items.

Particularly for large and profoundly nested information structures, heavy copy, a recursive procedure, tin beryllium slower and usage much memory. However, it ensures full independency betwixt nan original and nan heavy duplicate, making intricate information manipulation much secure.

The Best Copy Option for Your Data

Many programming languages usage nan conception of shallow and heavy copy. Understanding it lets you manipulate information without unforeseen consequences.

By utilizing shallow and heavy transcript techniques, you tin prime nan champion attack to copy your information structures safely. By knowing nan effects connected your data, you’ll get much dependable and predictable outcomes from your code.

Source Tutorials
Tutorials