Course contentsShow
← Python
Lesson 26 of 1,0601. Foundations and EnvironmentFree lesson

Creating Shallow Copies of Mutable Objects

You will use slicing or the copy module to create independent objects, preventing unintended side effects when modifying shared mutable data.

In this lesson, you will learn how to create a "shallow copy" of a mutable object to ensure that modifying one variable doesn't accidentally change another.

The Problem with Shared References

As we learned previously, when you assign one variable to another (e.g., list_b = list_a), you aren't creating a new copy. You are simply giving the existing object a second name. Because lists are mutable, changing list_b also changes list_a because they both point to the exact same place in memory. If you want to change one without affecting the other, you must create a new object.

Creating a Shallow Copy with Slicing

The most common way to create a shallow copy of a list is by using the slicing syntax [:]. This tells Python to create a brand-new list containing all the items from the original.

original = [1, 2, 3]
copy_list = original[:]  # Creates a shallow copy

copy_list.append(4)

print(original)   # Output: [1, 2, 3]
print(copy_list)  # Output: [1, 2, 3, 4]

By using [:], we forced Python to allocate new memory for copy_list. Even though both lists contain the same items, they are now independent objects.

Using the Copy Module

For more explicit control, Python provides a built-in copy module. You can use the copy() function to achieve the same result:

import copy

original = [10, 20, 30]
new_list = copy.copy(original)

new_list[0] = 99

print(original)  # Output: [10, 20, 30]
print(new_list)  # Output: [99, 20, 30]

A shallow copy creates a new container, but it does not copy the objects inside the container if they are also mutable (like a list inside a list). However, for simple collections of numbers or strings, this is the perfect way to prevent unintended side effects when modifying data.

Key Takeaway: To create a truly independent copy of a mutable object, use slicing [:] or the copy.copy() function to ensure your modifications stay isolated to the specific variable you intend to change.