Create an account


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

#1
Python List remove()

<div><p>This tutorial shows you everything you need to know to help you master the essential <code>remove()</code> method of the most fundamental container data type in the Python programming language.</p>
<p><strong>Definition and Usage</strong>:</p>
<p><strong>The <code>list.remove(element)</code> method removes the first occurrence of the <code>element</code> from an existing <code>list</code>.</strong> It does not, however, remove all occurrences of the element in the list!</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, 99, 4, 99]
>>> lst.remove(99)
>>> lst
[1, 2, 4, 99]</pre>
<p>In the first line of the example, you create the list <code>lst</code>. You then remove the integer element 99 from the list—but only its first occurrence. The result is the list with only four elements <code>[1, 2, 4, 99]</code>.</p>
<p>Try it yourself:</p>
<p> <iframe src="https://repl.it/repls/PotableOnerlookedDiscussions?lite=true" scrolling="no" allowtransparency="true" allowfullscreen="true" sandbox="allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals" width="100%" height="500px" frameborder="no"></iframe> </p>
<p><strong>Syntax</strong>:</p>
<p>You can call this method on each list object in Python. Here’s the syntax:</p>
<p><code>list.remove(element)</code></p>
<p><strong>Arguments:</strong></p>
<figure class="wp-block-table is-style-stripes">
<table>
<thead>
<tr>
<th>Argument</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>element</code></td>
<td>Object you want to remove from the list. Only the first occurrence of the element is removed.</td>
</tr>
</tbody>
</table>
</figure>
<p><strong>Return value:</strong></p>
<p>The method <code>list.remove(element)</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>
<p><strong>Code Puzzle:</strong></p>
<p>Now you know the basics. Let’s deepen your understanding with a short code puzzle—can you solve it?</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=""># Puzzle
presidents = ['Obama', 'Trump', 'Washington']
p2 = presidents[:2]
p2.remove('Trump')
print(presidents)
# What's the output of this code snippet?</pre>
<p>You can check out the solution on the <a href="https://app.finxter.com/learn/computer/science/447" target="_blank" rel="noreferrer noopener">Finxter app</a>.</p>
<p><strong>Overview</strong>:</p>
<p>There are some alternative ways 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>lst.remove(x)</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>
<p>Next, you’ll dive into each of those methods to gain some deep understanding.</p>
<h2>remove() — Remove An Element by Value</h2>
<p>To remove an element from the list, use the <code>list.remove(element)</code> method you’ve already seen previously:</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 = ["Alice", 3, "alice", "Ann", 42]
>>> lst.remove("Ann")
>>> lst
['Alice', 3, 'alice', 42]</pre>
<p>Try it yourself:</p>
<figure><iframe src="https://repl.it/repls/CurlyIdioticChief?lite=true" allowfullscreen="true" width="100%" height="400px"></iframe></figure>
<p>The method goes from left to right and removes the first occurrence of the element that’s <a rel="noreferrer noopener" href="https://docs.python.org/2.3/ref/comparisons.html" target="_blank">equal</a> to the one to be removed. </p>
<h3>Removed Element Does Not Exist</h3>
<p>If you’re trying to remove element x from the list but x does not exist in the list, Python throws a Value error:</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 = ['Alice', 'Bob', 'Ann']
>>> lst.remove('Frank')
Traceback (most recent call last): File "&lt;pyshell#19>", line 1, in &lt;module> lst.remove('Frank')
ValueError: list.remove(x): x not in list</pre>
<h2>pop() — Remove An Element by Index</h2>
<figure><iframe src="https://repl.it/repls/CurlyIdioticChief?lite=true" allowfullscreen="true" width="100%" height="600px"></iframe></figure>
<p>Per default, the <code>pop()</code> method removes the last element from the list and returns the element.</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 = ['Alice', 'Bob', 'Ann']
>>> lst.pop() 'Ann'
>>> lst
['Alice', 'Bob']</pre>
<p>But you can also define the optional index argument. In this case, you’ll remove the element at the given index—a little known Python secret!</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 = ['Alice', 'Bob', 'Ann']
>>> lst.pop(1) 'Bob'
>>> lst
['Alice', 'Ann']</pre>
<h2>clear() — Remove All Elements</h2>
<figure><iframe src="https://repl.it/repls/TightWiseTechnician?lite=true" allowfullscreen="true" width="100%" height="400px"></iframe></figure>
<p>The <code>clear()</code> method simply removes all elements from a given 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 = ['Alice', 'Bob', 'Ann']
>>> lst.clear()
>>> lst
[]</pre>
<h2>del — Remove Elements by Index or Slice</h2>
<figure><iframe src="https://repl.it/repls/ClientsideForsakenFrontpage?lite=true" allowfullscreen="true" width="100%" height="700px"></iframe></figure>
<p>This trick is also relatively unknown among Python beginners:</p>
<ul>
<li>Use <code>del lst[index]</code> to remove the element at index.</li>
<li>Use <code>del lst[startConfusedtop]</code> to remove all elements in the <a rel="noreferrer noopener" href="https://blog.finxter.com/introduction-to-slicing-in-python/" target="_blank">slice</a>.</li>
</ul>
<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 = list(range(10))
>>> lst
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> del lst[5]
>>> lst
[0, 1, 2, 3, 4, 6, 7, 8, 9]
>>> del lst[:4]
>>> lst
[4, 6, 7, 8, 9]</pre>
<p><strong>Related blog articles:</strong></p>
<ul>
<li><a rel="noreferrer noopener" href="https://blog.finxter.com/introduction-to-slicing-in-python/" target="_blank">Check out my full slicing tutorial that makes you a master slicer in 15 minutes or so!</a></li>
</ul>
<h2>List Comprehension — Remove Elements Conditionally</h2>
<figure><iframe src="https://repl.it/repls/FabulousMadEquation?lite=true" allowfullscreen="true" width="100%" height="400px"></iframe></figure>
<p>Okay, this is kind of cheating because this method does not really remove elements from a list object. It merely creates a new list with some elements that meet your condition. </p>
<p><strong>List comprehension is a compact way of creating lists. The simple formula is [ expression + context ].</strong></p>
<ul>
<li><strong>Expression: What to do with each list element?</strong></li>
<li><strong>Context: What list elements to select? It consists of an arbitrary number of for and if statements.</strong></li>
</ul>
<p><strong>The example <code>[x for x in range(3)]</code> creates the list <code>[0, 1, 2]</code>.</strong></p>
<p>You can also define a condition such as all odd values <code>x%2==1</code> in the context part by using an if condition. This leads us to a way to remove all elements that do not meet a certain condition in a given 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="">>>> lst = list(range(10))
>>> lst_new = [x for x in lst if x%2]
>>> lst_new
[1, 3, 5, 7, 9] </pre>
<p>While you iterate over the whole list <code>lst</code>, the condition <code>x%2</code> requires that the elements are odd.</p>
<p><strong>Related blog articles:</strong></p>
<ul>
<li><a href="https://blog.finxter.com/list-comprehension/" target="_blank" rel="noreferrer noopener">Check out my full list comprehension tutorial for maximal learning!</a></li>
</ul>
<h2>Python List remove() All</h2>
<p>The <code>list.remove(x)</code> method only removes the first occurrence of element <code>x</code> from the list. </p>
<p>But what if you want to remove all occurrences of element <code>x</code> from a given list? </p>
<p>The answer is to use a simple loop:</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 = ['Ann', 'Ann', 'Ann', 'Alice', 'Ann', 'Bob']
x = 'Ann' while x in lst: lst.remove(x) print(lst)
# ['Alice', 'Bob']</pre>
<p>You simply call the <code>remove()</code> method again and again until element <code>x</code> is not in the list anymore.</p>
<h2>Python List Remove Duplicates</h2>
<figure><iframe src="https://repl.it/repls/GrandioseRemarkableBackups?lite=true" allowfullscreen="true" width="100%" height="400px"></iframe></figure>
<p>How to remove all duplicates of a given value in the list?</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>Python List remove() If Exists</h2>
<p>How to remove an element from a list—but only if it exists?</p>
<p>The problem is that if you try to remove an element from the list that doesn’t exist, Python throws a <code>Value Error</code>. You can avoid this by checking the membership of the element to be removed first:</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 = ['Alice', 'Bob', 'Ann']
>>> lst.remove('Frank') if 'Frank' in lst else None
>>> lst
['Alice', 'Bob', 'Ann']</pre>
<p>This makes use of the Python one-liner feature of conditional assignment (also called the ternary operator).</p>
<p><strong>Related blog articles:</strong></p>
<ul>
<li><a href="https://blog.finxter.com/if-then-else-in-one-line-python/" target="_blank" rel="noreferrer noopener">Check out my ternary operator tutorial and boost your skills!</a></li>
</ul>
<h2>Python List remove() 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>remove()</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>remove()</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>Where to Go From Here?</h2>
<p>The <code>list.remove(element)</code> method removes the first occurrence of <code>element</code> 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/...st-remove/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016