![]() |
|
[Tut] List Changes After Assignment — How to Clone or Copy It? - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] List Changes After Assignment — How to Clone or Copy It? (/thread-97456.html) |
[Tut] List Changes After Assignment — How to Clone or Copy It? - xSicKxBot - 09-26-2020 List Changes After Assignment — How to Clone or Copy It? 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![]() The following interactive tool visualizes the memory used by the Python interpreter when executing this particular code snippet: https://pythontutor.com/iframe-embed.html#code=old_list%20%3D%20%5B'Alice',%20'Bob',%20'Carl'%5D%0Anew_list%20%3D%20old_list%0Anew_list.append%2842%29%0Aprint%28old_list%29%0A%23%20%5B'Alice',%20'Bob',%20'Carl',%2042%5D&codeDivHeight=400&codeDivWidth=350&cumulative=false&curInstr=2&heapPrimitives=nevernest&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=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]
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. |