Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python List clear()

#1
Python List clear()

<div><p>Surprisingly, even advanced Python coders don’t know about the <code>clear()</code> method of Python lists. Time to change that!</p>
<p><strong>Definition and Usage</strong>: <strong>The <code>list.clear()</code> method removes all elements from an existing <code>list</code>.</strong> The list becomes empty again.</p>
<p>Here’s a short 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="">>>> lst = [1, 2, 3, 4, 5]
>>> lst.clear()
>>> lst
[]</pre>
<p>In the first line, you create the list <code>lst</code> consisting of five integers. You then remove all elements from the list. The result is the empty list.</p>
<p><strong>Puzzle – Try It Yourself:</strong></p>
<p> <iframe height="700px" width="100%" src="https://repl.it/repls/PeacefulLimegreenBucket?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><strong>Syntax</strong>: You can call this method on each list object in Python. Here’s the syntax:</p>
<p><code>list.clear()</code></p>
<p><strong>Arguments:</strong> The method doesn’t take any argument.</p>
<p><strong>Return value:</strong> The method <code>list.clear()</code> has return value <code>None</code>. It operates on an existing list and, therefore, doesn’t return a new list with the removed element</p>
<p><strong>Video:</strong></p>
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-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 clear()" width="1400" height="788" src="https://www.youtube.com/embed/fqscJGzsDKc?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div>
</figure>
<h2>Python List clear() vs New List</h2>
<p>Now, if you’re an alert reader, you may ask the following interesting question: why to use the clear() method in the first place when you also can simply create a new list and be done with it?</p>
<p>Here’s an example where both ways lead to the same result:</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="">>>> lst = [1, 2, 3]
>>> lst.clear()
>>> lst
[]
>>> lst = [1, 2, 3]
>>> lst = []
>>> lst
[]</pre>
<p>I know the code seems to be a bit odd but it shows that instead of clearing an existing list, you can also create a new list. In this case, this leads to the exact same result. </p>
<p>However, Python is an object-oriented language. And if you just create a new object and assign it to a variable, the original list still exists in memory. And other variables may point to the object. </p>
<p>Consider the following code snippet that exemplifies this:</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="">lst = [1, 2, 3]
lst_2 = lst
lst = []
print(lst_2)
# [1, 2, 3]</pre>
<p>I’ve created a Python visualization for you so that you can see the objects in memory:</p>
<figure><iframe src="http://pythontutor.com/iframe-embed.html#code=lst%20%3D%20%5B1,%202,%203%5D%0Alst_2%20%3D%20lst%0Alst%20%3D%20%5B%5D%0Aprint%28lst_2%29&amp;codeDivHeight=400&amp;codeDivWidth=350&amp;cumulative=false&amp;curInstr=3&amp;heapPrimitives=nevernest&amp;origin=opt-frontend.js&amp;py=3&amp;rawInputLstJSON=%5B%5D&amp;textReferences=false" width="800" height="500"></iframe></figure>
<p>Simply assigning a new list to the variable <code>lst</code> will leave the other variable <code>lst_2</code> unaffected. Instead, you should have used lst.clear() to make sure that both variables now point to the same empty list object.</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="">lst = [1, 2, 3]
lst_2 = lst
lst.clear()
print(lst_2)
# []</pre>
<h2>Python List clear() Memory</h2>
<p>The effect of the <code>clear()</code> method is that the list is now empty. </p>
<p>In theory, you released the Python virtual machine from the burden of keeping the elements in the memory. Python uses <a rel="noreferrer noopener" href="https://en.wikipedia.org/wiki/Reference_counting" target="_blank">reference counting</a> to determine if some elements in the memory are not referenced anymore (and, thus, can be considered unused). Those elements will be removed—we say, they are <em><strong>deallocated</strong></em> from memory. If you clear the list, you essentially remove all references from the list to the list elements. However, some old list elements may still be referenced from the outside (e.g. by another variable). So they are not necessarily removed because they may still be needed! Just keep this in mind when clearing the list.</p>
<p>In practice, however, even referenced elements may still exist in the memory until the <a rel="noreferrer noopener" href="https://docs.python.org/3/library/gc.html" target="_blank">Python garbage collector</a> (or even the operating system) removes the elements from memory. </p>
<h2>Python List clear() Complexity</h2>
<p><strong>The <a href="https://en.wikipedia.org/wiki/Time_complexity" target="_blank" rel="noreferrer noopener">runtime complexity</a> of <code>list.clear()</code> is <code>O(n)</code> for a list with <code>n</code> elements.</strong> Why? Well, you first need to understand what happens if you remove all elements from a list. The list elements are not physically (or, for that matter, digitally) stored in the list. The list contains only references to the real list element objects in memory. If you clear the list, you remove all those references. </p>
<p>The <a rel="noreferrer noopener" href="https://docs.python.org/3/library/gc.html" target="_blank">garbage collector</a> in Python goes over all elements in the memory to remove the ones that have a reference count of zero. Why? Because they are the ones that cannot be accessed in the code. Thus, the garbage collector can safely assume that they are unused and are not needed anymore. As you see, the garbage collector needs the reference count information for each element in memory.</p>
<p>The algorithm when clearing a list is simple: <em>reduce the reference count of each list element object by one</em>. The objects that end up with reference count zero can now be removed from memory.<strong><em> But as you need to go over all list elements, the runtime complexity is linear to the list size.</em></strong></p>
<h2>Python List clear() Not Working</h2>
<p>The Python <code>list.clear()</code> method was added in Python 3.3 (<a rel="noreferrer noopener" href="https://docs.python.org/3/whatsnew/3.3.html" target="_blank">official source</a>). So if you try to use it for any Python version before that, you must use the <code>del list[:]</code> method that is semantically equivalent and works for earlier Python versions, too. </p>
<p><strong>Related articles on the Finxter blog:</strong></p>
<ul>
<li><a href="https://blog.finxter.com/how-to-check-your-python-version/" target="_blank" rel="noreferrer noopener">How to Check Your Python Version?</a></li>
</ul>
<h2>Python List clear() Version 2.7</h2>
<p>Have you tried to use Python <code>list.clear()</code> in Python 2.7? It’s not possible. The <code>clear()</code> method was added in Python 3.3 (<a rel="noreferrer noopener" href="https://docs.python.org/3/whatsnew/3.3.html" target="_blank">official source</a>). So if you try to use it for any Python version before that (including 2.7), you must use the <code>del list[:]</code> method that is semantically equivalent and works for earlier Python versions, too. </p>
<p><strong>Related articles on the Finxter blog:</strong></p>
<ul>
<li><a href="https://blog.finxter.com/how-to-check-your-python-version/" target="_blank" rel="noreferrer noopener">How to Check Your Python Version?</a></li>
</ul>
<h2>Python List clear() vs del</h2>
<p><strong>You may ask: what’s the difference between the <code>list.clear()</code> method and the <code>del</code> operation? </strong></p>
<p><strong>The answer is simple: there isn’t any semantic difference. The <code>list.clear()</code> method is just syntactical sugar for <code>del list[:]</code> (<a rel="noreferrer noopener" href="https://docs.python.org/3.6/tutorial/datastructures.html" target="_blank">source</a>). </strong></p>
<p>Here’s an example demonstrating that both are, in fact, the same:</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="">>>> lst = [1, 2, 3]
>>> lst.clear()
>>> lst
[]
>>> lst = [1, 2, 3]
>>> del lst[:]
>>> lst
[]</pre>
<h2>List Removal Alternatives</h2>
<p>There are some alternative <a href="https://blog.finxter.com/python-list-methods/" target="_blank" rel="noreferrer noopener">list methods</a> to remove elements from the list. See the overview table:</p>
<figure class="wp-block-table is-style-stripes">
<table>
<thead>
<tr>
<th>Method</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><code><a href="https://blog.finxter.com/python-list-remove/" target="_blank" rel="noreferrer noopener">lst.remove(x)</a></code></td>
<td>Remove an element from the list (by value)</td>
</tr>
<tr>
<td><code>lst.pop()</code></td>
<td>Remove an element from the list (by index) and return the element</td>
</tr>
<tr>
<td><code>lst.clear()</code></td>
<td>Remove all elements from the list</td>
</tr>
<tr>
<td><code>del lst[3]</code></td>
<td>Remove one or more elements from the list (by index or slice)</td>
</tr>
<tr>
<td>List comprehension</td>
<td>Remove all elements that meet a certain condition</td>
</tr>
</tbody>
</table>
</figure>
<h2>Python List clear() Thread Safe</h2>
<p>Do you have a multiple threads that access your list at the same time? Then you need to be sure that the list operations (such as <code>clear()</code>) are actually <a rel="noreferrer noopener" href="https://en.wikipedia.org/wiki/Thread_safety" target="_blank">thread safe</a>. </p>
<p>In other words: can you call the <code>clear()</code> operation in two threads on the same list at the same time? (And can you be sure that the result is meaningful?)</p>
<p>The answer is yes (if you use the <a href="https://github.com/python/cpython" target="_blank" rel="noreferrer noopener">cPython </a>implementation). The reason is Python’s <a rel="noreferrer noopener" href="https://wiki.python.org/moin/GlobalInterpreterLock" target="_blank">global interpreter lock</a> that ensures that a thread that’s currently working on it’s code will first finish its current basic Python operation as defined by the cPython implementation. Only if it terminates with this operation will the next thread be able to access the computational resource. This is ensured with a sophisticated locking scheme by the cPython implementation. </p>
<p>The only thing you need to know is that each basic operation in the cPython implementation is <a rel="noreferrer noopener" href="https://en.wikipedia.org/wiki/Atomicity_(database_systems)" target="_blank">atomic</a>. It’s executed wholly and at once before any other thread has the chance to run on the same virtual engine. Therefore, there are no race conditions. An example for such a race condition would be the following: the first thread reads a value from the list, the second threads overwrites the value, and the first thread overwrites the value again invalidating the second thread’s operation.</p>
<p><strong>All cPython operations are thread-safe. </strong>But if you combine those operations into higher-level functions, those are not generally thread safe as they consist of many (possibly interleaving) operations.</p>
<h2>Python List Clear Duplicates</h2>
<p><strong><em>How to remove all duplicates of a given value in the list?</em></strong></p>
<p>The naive approach is to go over each element and check whether this element already exists in the list. If so, remove it. However, this takes a few lines of code. </p>
<p>A shorter and more concise way is to create a dictionary out of the elements in the list. Each list element becomes a new key to the dictionary. All elements that occur multiple times will be assigned to the same key. The dictionary contains only unique keys—there cannot be multiple equal keys.</p>
<p>As dictionary values, you simply take dummy values (per default).</p>
<p><strong>Related blog articles:</strong></p>
<ul>
<li><a rel="noreferrer noopener" href="https://blog.finxter.com/python-dictionary/" target="_blank">Check out my ultimate dictionary tutorial for maximal learning!</a></li>
</ul>
<p>Then, you simply convert the dictionary back to a list throwing away the dummy values. As the dictionary keys stay in the same order, you don’t lose the order information of the original list elements. </p>
<p>Here’s the code:</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="">>>> lst = [1, 1, 1, 3, 2, 5, 5, 2]
>>> dic = dict.fromkeys(lst)
>>> dic
{1: None, 3: None, 2: None, 5: None}
>>> duplicate_free = list(dic)
>>> duplicate_free
[1, 3, 2, 5]</pre>
<h2>Where to Go From Here?</h2>
<p>The <code>list.clear()</code> method removes all elements from the <code>list</code>.</p>
<p>You’ve learned the ins and outs of this important <a rel="noreferrer noopener" href="https://blog.finxter.com/python-list-methods/" target="_blank">Python list method</a>.</p>
<p>If you keep struggling with those basic Python commands and you feel stuck in your learning progress, I’ve got something for you: <a rel="noreferrer noopener" href="https://www.amazon.com/gp/product/B07ZY7XMX8" target="_blank">Python One-Liners</a> (Amazon Link). </p>
<p>In the book, I’ll give you a thorough overview of critical computer science topics such as machine learning, regular expression, data science, NumPy, and Python basics—all in a single line of Python code!</p>
<p><a rel="noreferrer noopener" href="https://www.amazon.com/gp/product/B07ZY7XMX8" target="_blank">Get the book from Amazon!</a></p>
<p><strong>OFFICIAL BOOK DESCRIPTION:</strong> <em>Python One-Liners will show readers how to perform useful tasks with one line of Python code. Following a brief Python refresher, the book covers essential advanced topics like slicing, list comprehension, broadcasting, lambda functions, algorithms, regular expressions, neural networks, logistic regression and more. Each of the 50 book sections introduces a problem to solve, walks the reader through the skills necessary to solve that problem, then provides a concise one-liner Python solution with a detailed explanation.</em></p>
</div>


https://www.sickgaming.net/blog/2020/03/...ist-clear/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016