Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] List Changes After Assignment — How to Clone or Copy It?

#1
List Changes After Assignment — How to Clone or Copy It?

<div><p><strong>Problem</strong>: If you assign a list object to a new variable using <code>new_list = old_list</code>, any modification to <code>new_list</code> changes <code>old_list</code>. What’s the reason for this and how can you clone or copy the <a href="https://blog.finxter.com/python-lists/" target="_blank" rel="noreferrer noopener" title="The Ultimate Guide to Python Lists">list </a>to prevent this problem?</p>
<p><strong>Example</strong>: Let’s consider the following example.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">old_list = ['Alice', 'Bob', 'Carl']
new_list = old_list
new_list.append(42)
print(old_list)
# ['Alice', 'Bob', 'Carl', 42]
</pre>
<p>Appending an element to the <code>new_list</code> also modifies the original list <code>old_list</code>. Thus, <code>old_list</code> has now four elements—even though you didn’t change it directly.</p>
<h2>Explanation</h2>
<p>This problem of simultaneously modifying “two” lists arises because you don’t have two lists but only a single one. </p>
<p>In Python, everything is an object. You create a new list object <code>['Alice', 'Bob', 'Carl']</code> that resides in your machine’s memory. Both variable names <code>new_list</code> and <code>old_list</code> point to the same object in memory—if you modify one, you also modify the other!</p>
<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img loading="lazy" src="https://blog.finxter.com/wp-content/uploads/2020/09/list_same_obj_reference-1024x576.jpg" alt="List Changes After Assignment -- How to Clone or Copy It?" class="wp-image-13783" width="768" height="432" srcset="https://blog.finxter.com/wp-content/uploads/2020/09/list_same_obj_reference-scaled.jpg 1024w, https://blog.finxter.com/wp-content/uplo...00x169.jpg 300w, https://blog.finxter.com/wp-content/uplo...68x432.jpg 768w, https://blog.finxter.com/wp-content/uplo...150x84.jpg 150w" sizes="(max-width: 768px) 100vw, 768px" /></figure>
</div>
<p>The following interactive tool visualizes the memory used by the Python interpreter when executing this particular code snippet:</p>
<p> <iframe width="800" height="500" frameborder="0" src="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"> </iframe> </p>
<p><em><strong>Exercise</strong>: Visualize how the problem arises by clicking “Next”. </em></p>
<p>Do you understand the source of the problem? Great, let’s dive into the solutions starting with a short overview!</p>
<h2>Solution Overview</h2>
<p>You can see all three solutions discussed in this tutorial in our interactive Python shell:</p>
<p> <iframe height="800px" width="100%" src="https://repl.it/@finxter/FaintCheapButton?lite=true" scrolling="no" frameborder="no" allowtransparency="true" allowfullscreen="true" sandbox="allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals"></iframe> </p>
<p><em><strong>Exercise</strong>: Change the original list. Do all three methods still produce the same output?</em></p>
<p>Next, you’ll learn about each method in greater detail!</p>
<h2>Method 1: Slicing</h2>
<p>The easiest way to create a <a href="https://blog.finxter.com/copy-list-of-lists-in-python-shallow-vs-deep/" title="How to Copy List of Lists in Python (Shallow vs Deep)?" target="_blank" rel="noreferrer noopener">shallow copy</a> of a Python list is via <a href="https://blog.finxter.com/introduction-to-slicing-in-python/" title="Introduction to Slicing in Python">slicing</a>:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Method 1: Slicing
old_list = ['Alice', 'Bob', 'Carl']
new_list = old_list[:]
new_list.append(42)
print(new_list)
# ['Alice', 'Bob', 'Carl']</pre>
<p>The slicing operation <code>old_list[:]</code> creates a new list, so the variables <code>new_list</code> and <code>old_list</code> now point to different objects in memory. If you change one, the other doesn’t change. </p>
<p>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.</p>
<p><strong>Related Tutorial</strong>: <a href="https://blog.finxter.com/introduction-to-slicing-in-python/" target="_blank" rel="noreferrer noopener" title="Introduction to Slicing in Python">Introduction to Slicing in Python</a></p>
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<div class="ast-oembed-container"><iframe title="The Ultimate Guide to Slicing in Python" width="1400" height="788" src="https://www.youtube.com/embed/D2ZueuWXST8?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div>
</figure>
<h2>Method 2: Copy</h2>
<p>An alternative is to use the <code><a href="https://blog.finxter.com/python-list-copy/" title="Python List copy()">list.copy()</a></code> method that creates a shallow copy of the list.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Method 2: Copy
old_list = ['Alice', 'Bob', 'Carl']
new_list = old_list.copy()
new_list.append(42)
print(old_list)
# ['Alice', 'Bob', 'Carl']</pre>
<p>The <code>list.copy()</code> method copies all <code>list</code> 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.</p>
<p>The result is the same as the slicing method: you have two variables pointing to two different list objects in memory. </p>
<p>You can learn more about the <code>list.copy()</code> method in my detailed blog tutorial and the following video:</p>
<p><strong>Related Tutorial:</strong> <a href="https://blog.finxter.com/python-list-copy/" title="Python List copy()" target="_blank" rel="noreferrer noopener">Python <code>list.copy()</code> [Ultimate Guide]</a></p>
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<div class="ast-oembed-container"><iframe title="Python List copy()" width="1400" height="788" src="https://www.youtube.com/embed/VhLrz7ivZbc?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div>
</figure>
<h2>Method 3: List Comprehension</h2>
<p>A third way to solve the problem of two lists pointing to the same object in memory is the <a href="https://blog.finxter.com/list-comprehension/" title="List Comprehension in Python — A Helpful Illustrated Guide" target="_blank" rel="noreferrer noopener">list comprehension</a> way to <a href="https://blog.finxter.com/how-to-create-a-python-list/" target="_blank" rel="noreferrer noopener" title="How to Create a Python List?">create new lists</a>. </p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># 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']</pre>
<p>List comprehension is a compact way of creating lists. The simple formula is <code>[expression + context]</code>.</p>
<ul>
<li><strong>Expression: </strong>What to do with each list element?</li>
<li><strong>Context: </strong>What elements to select? The context consists of an arbitrary number of <code>for</code> and <code>if</code> statements.</li>
</ul>
<p>You can watch the tutorial video and read over the related blog article to learn more about it!</p>
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<div class="ast-oembed-container"><iframe title="A Simple Introduction to List Comprehension in Python" width="1400" height="788" src="https://www.youtube.com/embed/9qsq2Vf48W8?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div>
</figure>
<p><strong>Related Tutorial:</strong> <a href="https://blog.finxter.com/list-comprehension/" target="_blank" rel="noreferrer noopener" title="List Comprehension in Python — A Helpful Illustrated Guide">An Introduction to List Comprehension</a></p>
<h2 class="wp-block-block">Where to Go From Here?</h2>
<p>Enough theory, let’s get some practice!</p>
<p>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?</p>
<p><strong>Practice projects is how you sharpen your saw in coding!</strong></p>
<p>Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?</p>
<p>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.</p>
<p>Join my free webinar <a rel="noreferrer noopener" href="https://blog.finxter.com/webinar-freelancer/" target="_blank">“How to Build Your High-Income Skill Python”</a> and watch how I grew my coding business online and how you can, too—from the comfort of your own home.</p>
<p><a href="https://blog.finxter.com/webinar-freelancer/" target="_blank" rel="noreferrer noopener">Join the free webinar now!</a></p>
<p>The post <a href="https://blog.finxter.com/list-changes-after-assignment-clone-copy/" target="_blank" rel="noopener noreferrer">List Changes After Assignment — How to Clone or Copy It?</a> first appeared on <a href="https://blog.finxter.com/" target="_blank" rel="noopener noreferrer">Finxter</a>.</p>
</div>


https://www.sickgaming.net/blog/2020/09/...r-copy-it/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016