09-26-2020, 09:14 PM
List Changes After Assignment — How to Clone or Copy It?
Problem: If you assign a list object to a new variable using, any modification to changes . What’s the reason for this and how can you clone or copy the listto prevent this problem?
Example: Let’s consider the following example.
Appending an element to the also modifies the original list . Thus, has now four elements—even though you didn’t change it directly.
Explanation
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 that resides in your machine’s memory. Both variable names and point to the same object in memory—if you modify one, you also modify the other!
![[Image: list_same_obj_reference-1024x576.jpg]](https://blog.finxter.com/wp-content/uploads/2020/09/list_same_obj_reference-1024x576.jpg)
The following interactive tool visualizes the memory used by the Python interpreter when executing this particular code snippet:
https://pythontutor.com/iframe-embed.htm...nces=false
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!
Solution Overview
You can see all three solutions discussed in this tutorial in our interactive Python shell:
https://repl.it/@finxter/FaintCheapButton?lite=true
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:
The slicing operation creates a new list, so the variables and 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 method that creates a shallow copy of the list.
The method copies all 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 method in my detailed blog tutorial and the following video:
Related Tutorial: Python [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.
List comprehension is a compact way of creating lists. The simple formula is.
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.
Join the free webinar now!
The post List Changes After Assignment — How to Clone or Copy It? first appeared on Finxter.
Problem: If you assign a list object to a new variable using
Code:
new_list = old_listCode:
new_listCode:
old_listExample: Let’s consider the following example.
Code:
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
Code:
new_listCode:
old_listCode:
old_listExplanation
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
Code:
['Alice', 'Bob', 'Carl']Code:
new_listCode:
old_list![[Image: list_same_obj_reference-1024x576.jpg]](https://blog.finxter.com/wp-content/uploads/2020/09/list_same_obj_reference-1024x576.jpg)
The following interactive tool visualizes the memory used by the Python interpreter when executing this particular code snippet:
https://pythontutor.com/iframe-embed.htm...nces=false
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!
Solution Overview
You can see all three solutions discussed in this tutorial in our interactive Python shell:
https://repl.it/@finxter/FaintCheapButton?lite=true
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:
Code:
# 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
Code:
old_list[:]Code:
new_listCode:
old_listThis 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
Code:
list.copy()Code:
# Method 2: Copy
old_list = ['Alice', 'Bob', 'Carl']
new_list = old_list.copy()
new_list.append(42)
print(old_list)
# ['Alice', 'Bob', 'Carl']The
Code:
list.copy()Code:
listThe 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
Code:
list.copy()Related Tutorial: Python
Code:
list.copy()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.
Code:
# 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
Code:
[expression + context]- Expression: What to do with each list element?
- Context: What elements to select? The context consists of an arbitrary number of andCode:
forstatements.Code:if
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.
Join the free webinar now!
The post List Changes After Assignment — How to Clone or Copy It? first appeared on Finxter.

