Create an account


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

#1
Python List pop()

<div><p>This tutorial shows you everything you need to know to help you master the essential <code>pop()</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.pop()</code> method removes and returns the last element from an existing <code>list</code>. The <code>list.pop(index)</code> method with the optional argument <code>index</code> removes and returns the element at the position <code>index</code>. </strong></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]
>>> lst.pop()
3
>>> lst
[1, 2]</pre>
<p>In the first line of the example, you create the list <code>lst</code>. You then remove and return the final element 3 from the list. The result is the list with only two elements <code>[1, 2]</code>.</p>
<p><strong>Code Puzzle — Try It Yourself:</strong></p>
<p>Now you know the basics. Let’s deepen your understanding with a short code puzzle—can you solve it?</p>
<p> <iframe height="700px" width="100%" src="https://repl.it/repls/UsedSquareExperiments?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><a href="https://app.finxter.com/learn/computer/science/563" target="_blank" rel="noreferrer noopener">You can also solve this puzzle and track your Python skills on our interactive Finxter app.</a></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.pop(index=-1)</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>index</code></td>
<td>Optional argument. You can define the index of the element to be removed and returned. The default argument leads to the removal of the last list element with index -1. </td>
</tr>
</tbody>
</table>
</figure>
<p><strong>Return value:</strong></p>
<p>The method <code>list.pop()</code> has return value <code>Object</code>. It removes the respective element from the list (default: the last element) and returns it directly to the caller.</p>
<p><strong>Video:</strong></p>
<figure class="wp-block-embed-youtube wp-block-embed is-type-rich is-provider-embed-handler wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<div class="ast-oembed-container"><iframe title="Python List remove()" width="1400" height="788" src="https://www.youtube.com/embed/CjA4lX6cXKE?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</p></div>
</figure>
<h2>Python List pop() By Index</h2>
<p>You can use the <code>list.pop(index)</code> method to with the optional index argument to remove and return the element at position <code>index</code> from the list. </p>
<p>Here’s an 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="">>>> customers = ['Alice', 'Bob', 'Ann', 'Frank']
>>> customers.pop(2) 'Ann'
>>> customers
['Alice', 'Bob', 'Frank']
>>> customers.pop(0) 'Alice'
>>> customers
['Bob', 'Frank']</pre>
<p>After creating the list with four elements, you first remove and return the second element <code>'Ann'</code>. Then, you remove and return the first element <code>'Alice'</code>. The resulting list has only two elements left.</p>
<h2>Python List pop() First / Front / Left / Head</h2>
<p>The <code>list.pop(index)</code> method to with the optional index argument to remove and return the element at position <code>index</code> from the list. So if you want to remove the first element from the list, simply set <code>index=0</code> by calling <code>list.pop(0)</code>. This will pop the first element from the list.</p>
<p>Here’s an 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="">>>> primes = [1, 2, 3, 5, 7, 11]
>>> primes.pop(0)
1
>>> primes
[2, 3, 5, 7, 11]</pre>
<p>The <code>pop(0)</code> method removes the first element 1 from the list of prime numbers given in the example.</p>
<h2>Python List pop() By Value</h2>
<p>In the previous two examples, you’ve seen how to pop elements by index. But can you also pop by value?</p>
<p>Yes, you can by using the <code>list.index(value)</code> method which gives you the index of the element value in the list. Now, you can use the <code>list.pop(index)</code> method on this index to remove the value from the list and get the result as a return value.</p>
<p>Here’s an example where you want to pop the element 7 from the list and store the result in the variable <code>some_prime</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="">>>> primes = [1, 2, 3, 5, 7, 11]
>>> some_prime = primes.pop(primes.index(7))
>>> some_prime
7</pre>
<p>If you’re not interested in the return value but you only want to remove the first occurrence of the value <code>x</code> in the <code>list</code>, use the <code>list.remove(x)</code> method. </p>
<p><strong>Related Article:</strong></p>
<ul>
<li><a href="https://blog.finxter.com/python-list-remove/" target="_blank" rel="noreferrer noopener">Python List remove() </a></li>
</ul>
<h2>Python List pop() Multiple Elements</h2>
<h2>Python List pop() First n Elements</h2>
<h2>Python List pop() Last n Elements</h2>
<h2>Python List pop() Time Complexity … First and Last and General cases</h2>
<h2>Python List pop() vs remove()</h2>
<h2>Python List Pop and Push (Stack)</h2>
<h2>Python List pop() Without Remove</h2>
<h2>Python List pop() While Iterating</h2>
<h2>Python List pop() If Not Empty</h2>
<h2>Python List pop() Slice</h2>
</p>
<h2>Alternatives Ways to Remove Elements From a List</h2>
<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 pop() 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>pop()</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>pop()</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/...-list-pop/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016