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
# 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
# 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!
To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And 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?
Practice projects is how you sharpen your saw in coding!
Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?
Then become 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.
Join my free webinar “How to Build Your High-Income Skill Python” and watch 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. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, 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.