Problem: If you assign a list object to a new variable using
new_list = old_list, any modification to
old_list. What’s the reason for this and how can you clone or copy the list to prevent this problem?
Example: Let’s consider the following example.
old_list = ['Alice', 'Bob', 'Carl'] new_list = old_list new_list.append(42) print(old_list) # ['Alice', 'Bob', 'Carl', 42]
Appending an element to the
new_list also modifies the original list
old_list has now four elements—even though you didn’t change it directly.
This problem of simultaneously modifying “two” lists arises because you don’t have two lists but only a single one.
In Python, everything is an object. You create a new list object
['Alice', 'Bob', 'Carl'] that resides in your machine’s memory. Both variable names
old_list point to the same object in memory—if you modify one, you also modify the other!
The following interactive tool visualizes the memory used by the Python interpreter when executing this particular code snippet:
Exercise: Visualize how the problem arises by clicking “Next”.
Do you understand the source of the problem? Great, let’s dive into the solutions starting with a short overview!
You can see all three solutions discussed in this tutorial in our interactive Python shell:
Exercise: Change the original list. Do all three methods still produce the same output?
Next, you’ll learn about each method in greater detail!
Method 1: Slicing
The easiest way to create a shallow copy of a Python list is via slicing:
# Method 1: Slicing old_list = ['Alice', 'Bob', 'Carl'] new_list = old_list[:] new_list.append(42) print(new_list) # ['Alice', 'Bob', 'Carl']
The slicing operation
old_list[:] creates a new list, so the variables
old_list now point to different objects in memory. If you change one, the other doesn’t change.
This is the way with the least amount of characters and many Python coders would consider this the most Pythonic one. If you want to learn more about slicing, watch the following video and dive into the detailed blog tutorial.
Related Tutorial: Introduction to Slicing in Python
Method 2: Copy
An alternative is to use the
list.copy() method that creates a shallow copy of the list.
# Method 2: Copy old_list = ['Alice', 'Bob', 'Carl'] new_list = old_list.copy() new_list.append(42) print(old_list) # ['Alice', 'Bob', 'Carl']
list.copy() method copies all
list elements into a new list. The new list is the return value of the method. It’s a shallow copy—you copy only the object references to the list elements and not the objects themselves.
The result is the same as the slicing method: you have two variables pointing to two different list objects in memory.
You can learn more about the
list.copy() method in my detailed blog tutorial and the following video:
Related Tutorial: Python
list.copy() [Ultimate Guide]
Method 3: List Comprehension
A third way to solve the problem of two lists pointing to the same object in memory is the list comprehension way to create new lists.
# Method 3: List Comprehension old_list = ['Alice', 'Bob', 'Carl'] new_list = [x for x in old_list] new_list.append(42) print(old_list) # ['Alice', 'Bob', 'Carl']
List comprehension is a compact way of creating lists. The simple formula is
[expression + context].
- Expression: What to do with each list element?
- Context: What elements to select? The context consists of an arbitrary number of
You can watch the tutorial video and read over the related blog article to learn more about it!
Related Tutorial: An Introduction to List Comprehension
Where to Go From Here?
Enough theory. Let’s get some practice!
Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.
To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?
You build high-value coding skills by working on practical coding projects!
Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?
🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.
If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.