A2oz

How Do You Copy a Data Structure in Python?

Published in Python Data Structures 2 mins read

Copying a data structure in Python depends on whether you want a shallow copy or a deep copy.

Shallow Copy

A shallow copy creates a new object that references the same underlying data as the original object. This means that changes to the copied object will also affect the original object.

You can create a shallow copy using the following methods:

  • Slicing: This method works for lists, tuples, and strings.
      original_list = [1, 2, 3]
      shallow_copy = original_list[:]
  • copy() method: This method is available for mutable objects like lists, dictionaries, and sets.
      original_list = [1, 2, 3]
      shallow_copy = original_list.copy()

Deep Copy

A deep copy creates a new object that is completely independent of the original object. This means that changes to the copied object will not affect the original object.

You can create a deep copy using the copy module:

import copy

original_list = [1, 2, [3, 4]]
deep_copy = copy.deepcopy(original_list)

Practical Insights

  • Shallow copies are faster and use less memory than deep copies.
  • Use a shallow copy when you only need a temporary copy of the data and don't need to modify the original object.
  • Use a deep copy when you need a completely independent copy of the data that you can modify without affecting the original object.

Examples

Shallow Copy Example

original_list = [1, 2, [3, 4]]
shallow_copy = original_list[:]

shallow_copy[2][0] = 5

print(original_list)  # Output: [1, 2, [5, 4]]
print(shallow_copy)  # Output: [1, 2, [5, 4]]

Deep Copy Example

import copy

original_list = [1, 2, [3, 4]]
deep_copy = copy.deepcopy(original_list)

deep_copy[2][0] = 5

print(original_list)  # Output: [1, 2, [3, 4]]
print(deep_copy)  # Output: [1, 2, [5, 4]]

Related Articles