Mastering List Duplication

Learn how to effectively copy lists in Python, understanding the crucial difference between shallow and deep copies and their practical applications. …

Updated August 26, 2023



Learn how to effectively copy lists in Python, understanding the crucial difference between shallow and deep copies and their practical applications.

Imagine you have a beautifully organized shopping list in Python:

shopping_list = ["apples", "bananas", "milk"]

Now, let’s say you want to share this list with your roommate but also keep a copy for yourself. Simply assigning the list to a new variable won’t create a separate copy; it creates another reference pointing to the same list in memory:

roommates_list = shopping_list  # Both variables now point to the same list
roommates_list.append("eggs") 
print(shopping_list) # Output: ["apples", "bananas", "milk", "eggs"] 

Uh oh! Your roommate added eggs to their list, and now your copy has them too! This is because Python created a shallow copy. It copied the reference, not the actual list contents.

To avoid this unexpected behavior, we need a deep copy. A deep copy creates a completely independent replica of the original list, including all its elements.

Here’s how to do it using the copy module:

import copy

shopping_list = ["apples", "bananas", "milk"]
roommates_list = copy.deepcopy(shopping_list) 
roommates_list.append("eggs")

print(shopping_list)  # Output: ["apples", "bananas", "milk"]
print(roommates_list) # Output: ["apples", "bananas", "milk", "eggs"]

Now, your roommate can add eggs without affecting your copy!

Key Takeaways:

  • Shallow Copy: Creates a new reference to the same list in memory. Changes made through one reference affect all others.

  • Deep Copy: Creates an entirely independent copy of the list and its elements. Changes are isolated to the specific copy.

When to Use Each:

  • Shallow Copy: Useful when you want to share a list with another part of your code but don’t anticipate making changes that would impact the original.
  • Deep Copy: Essential when you need independent copies for modifications or complex data structures (lists within lists, dictionaries as values).

Let me know if you’d like to explore more advanced examples of copying lists, such as dealing with nested lists!


Stay up to date on the latest in Computer Vision and AI

Intuit Mailchimp