Guidelines

Differences Between Shallow and Deep Copy

In Python, an object is a fundamental unit that contains both data and the methods to handle that data.

In Python, nearly everything such as numbers, strings, and sets can be considered as objects.

There are two methods to copy an object: Shallow Copy and Deep Copy.

  • A shallow copy affects both the original and the copy when one is modified.

  • A deep copy means the original and the copy are completely independent, so changes to one will not affect the other.


Shallow Copy

A shallow copy shares the internal objects between the copied object and the original object.

If you modify the copied object, the original object will also change.

You can perform a shallow copy using the list() function to create a new list.

The code example below demonstrates that changing an element in the copied object also changes the original object.

Shallow Copy Example
# Create original list original = [1, 2, 3, [4, 5, 6]] # Perform a shallow copy and assign to 'shallow_copied' shallow_copied = list(original) # Modify nested list element in 'shallow_copied' shallow_copied[3][0] = 99 # The original list is also changed print("Original:", original) # [1, 2, 3, [99, 5, 6]]

In the above example, changing the nested list [4, 5, 6] in the shallow_copied list also changes the original original list.


Deep Copy

A deep copy creates new objects at every level of the hierarchy.

The copied object is completely independent of the original object, so modifying the original object does not affect the copied object.

The code example below demonstrates that modifying an element in the copied object does not affect the original object.

Deep Copy Example
# Import the 'copy' module import copy original = [1, 2, 3, [4, 5, 6]] deep_copied = copy.deepcopy(original) deep_copied[3][0] = 99 # Print results print("Original:", original) # Outputs [1, 2, 3, [4, 5, 6]] : the original list is unchanged print("Deep Copied:", deep_copied) # Outputs [1, 2, 3, [99, 5, 6]] : only the copied list is changed

In the above code, the import keyword helps to bring in external code so it can be used.

The copy module is built into Python and allows you to perform a deep copy using the copy.deepcopy() function.

Note: In programming, a Module is an external code file that is composed of functions, variables, classes, etc.

Mission
0 / 1

What is the most appropriate word for the blank below?

When the original object and the copied object share internal objects, so changing one affects the other, it is a [____] copy.
shallow
deep
complete
partial

Guidelines

AI Tutor

Publish

Design

Upload

Notes

Favorites

Help

Code Editor

Run
Generate

Execution Result