Understanding Shallow vs. Deep Copying in Tuples

Understanding Shallow vs. Deep Copying in Tuples

Shallow copying and deep copying are two ways to make copies of objects in Python. Let's look at the differences between them with examples, especially for tuples:

  1. Shallow Copying:

    • Shallow copying creates a new object but does not create copies of nested objects. Instead, it copies references to the nested objects.

    • If the original tuple contains mutable objects (like lists), changes made to the nested objects in the copied tuple will affect the original tuple and vice versa.

    • Shallow copying can be performed using the copy() method or the copy module's copy() function.

import copy

original_tuple = ([1, 2], [3, 4])
shallow_copy_tuple = copy.copy(original_tuple)

# Modifying the nested list in the shallow copy
shallow_copy_tuple[0].append(5)

print("Original Tuple:", original_tuple)   # Output: ([1, 2, 5], [3, 4])
print("Shallow Copy Tuple:", shallow_copy_tuple)   # Output: ([1, 2, 5], [3, 4])
  1. Deep Copying:

    • Deep copying creates a completely independent copy of the original object, including all nested objects. Changes made to the nested objects in the copied tuple do not affect the original tuple, and vice versa.

    • Deep copying can be performed using the deepcopy() function from the copy module.

import copy

original_tuple = ([1, 2], [3, 4])
deep_copy_tuple = copy.deepcopy(original_tuple)

# Modifying the nested list in the deep copy
deep_copy_tuple[0].append(5)

print("Original Tuple:", original_tuple)   # Output: ([1, 2], [3, 4])
print("Deep Copy Tuple:", deep_copy_tuple)   # Output: ([1, 2, 5], [3, 4])

In summary:

  • Shallow copying creates a new object with references to the nested objects, so changes to nested objects in one tuple affect the other.

  • Deep copying creates an entirely new object with copies of all nested objects, so changes to nested objects in one tuple do not affect the other.

Did you find this article valuable?

Support LingarajTechhub All About Programming by becoming a sponsor. Any amount is appreciated!