Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python Slice Remove First and Last Element from a List

#1
Python Slice Remove First and Last Element from a List

<div>
<div class="kk-star-ratings kksr-auto kksr-align-left kksr-valign-top" data-payload="{&quot;align&quot;:&quot;left&quot;,&quot;id&quot;:&quot;473156&quot;,&quot;slug&quot;:&quot;default&quot;,&quot;valign&quot;:&quot;top&quot;,&quot;reference&quot;:&quot;auto&quot;,&quot;class&quot;:&quot;&quot;,&quot;count&quot;:&quot;1&quot;,&quot;readonly&quot;:&quot;&quot;,&quot;score&quot;:&quot;5&quot;,&quot;best&quot;:&quot;5&quot;,&quot;gap&quot;:&quot;5&quot;,&quot;greet&quot;:&quot;Rate this post&quot;,&quot;legend&quot;:&quot;5\/5 - (1 vote)&quot;,&quot;size&quot;:&quot;24&quot;,&quot;width&quot;:&quot;142.5&quot;,&quot;_legend&quot;:&quot;{score}\/{best} - ({count} {votes})&quot;,&quot;font_factor&quot;:&quot;1.25&quot;}">
<div class="kksr-stars">
<div class="kksr-stars-inactive">
<div class="kksr-star" data-star="1" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="2" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="3" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="4" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="5" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
<div class="kksr-stars-active" style="width: 142.5px;">
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
</div>
<div class="kksr-legend" style="font-size: 19.2px;"> 5/5 – (1 vote) </div>
</div>
<h2>Problem Formulation</h2>
<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4ac.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Question</strong>: Given a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-lists/" data-type="post" data-id="7332" target="_blank">Python list</a> stored in a variable <code>lst</code>. How to remove the first and last elements from the list <code>lst</code>?</p>
<p><strong>Example</strong>: The list <code>['Alice', 'Bob', 'Carl', 'Dave']</code> stored in variable <code>lst</code> becomes <code>['Bob', 'Carl']</code>.</p>
<h2>Method 1: Slicing List[1:-1]</h2>
<p class="has-global-color-8-background-color has-background">To remove the first and last elements from a Python list, use the expression <code>lst = lst[1:-1]</code> that uses a Python feature called <a rel="noreferrer noopener" href="https://blog.finxter.com/introduction-to-slicing-in-python/" data-type="post" data-id="731" target="_blank">slicing</a> with the syntax <code>variable[start:stop]</code> to iterate over a sequence starting from the <code>start</code> index (included) and ending in the element at <code>stop</code> index (excluded). If <code>stop</code> is a negative integer such as <code>-i</code>, Python takes the i-th right-most element. </p>
<p>Here’s an example:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="2" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">lst = ['Alice', 'Bob', 'Carl', 'Dave']
lst = lst[1:-1]
print(lst)
# ['Bob', 'Carl']</pre>
<p>This code snippet removes the first element <code>'Alice'</code> and the last element <code>'Dave'</code> from the list.</p>
<p>Note that this approach also works for lists with one element:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="2" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">lst = ['Alice']
lst = lst[1:-1]
print(lst)
# []
</pre>
<p>… and also for an <a href="https://blog.finxter.com/how-to-create-an-empty-list-in-python/" data-type="post" data-id="453870" target="_blank" rel="noreferrer noopener">empty list</a> with zero elements:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="2" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">lst = []
lst = lst[1:-1]
print(lst)
# []
</pre>
<p>Feel free to get some background on slicing by watching the following tutorial:</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">
<iframe loading="lazy" title="The Ultimate Guide to Slicing in Python" width="780" height="439" 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>
</figure>
<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f30e.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Learn More</strong>: <a href="https://blog.finxter.com/introduction-to-slicing-in-python/" data-type="post" data-id="731" target="_blank" rel="noreferrer noopener">An Introduction to Python Slicing</a></p>
<h2>Method 2: Slicing List Without Negative Index</h2>
<p class="has-global-color-8-background-color has-background">To remove the first and last elements from a Python list, you can also use the slightly more complex expression <code>lst = lst[1:len(lst)-1]</code> that assigns the result of the slicing operation to the list and, thereby, overwrites the original longer list. We decrement the <code><a href="https://blog.finxter.com/python-len/" data-type="post" data-id="22386" target="_blank" rel="noreferrer noopener">len()</a></code> function result to obtain the index of the last element that is excluded from the slice.</p>
<p>Here’s an example:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="2" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">lst = ['Alice', 'Bob', 'Carl', 'Dave']
lst = lst[1:len(lst)-1]
print(lst)
# ['Bob', 'Carl']
</pre>
<p>You can watch my related tutorial video:</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">
<iframe loading="lazy" title="Python len() -- A Simple Guide" width="780" height="439" src="https://www.youtube.com/embed/WZYnweSv9yI?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
</figure>
<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f30e.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Learn More</strong>: <a rel="noreferrer noopener" href="https://blog.finxter.com/python-len/" data-type="URL" data-id="https://blog.finxter.com/python-len/" target="_blank">The Python <code>len()</code> function</a></p>
<h2>Method 3: list.pop() and list.pop(0)</h2>
<p class="has-global-color-8-background-color has-background">To remove the first element of a Python list, you can use the <code><a href="https://blog.finxter.com/python-list-pop/" data-type="post" data-id="6853">list.pop(0)</a></code> method. To remove the last element of a Python list, you can use the <code>list.pop()</code> method without argument. You can call both to remove the first and the last elements if the list has at least two elements. </p>
<p>Here’s a minimal example:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="2-3" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">lst = ['Alice', 'Bob', 'Carl', 'Dave']
lst.pop() # remove last
lst.pop(0) # remove first
print(lst)
# ['Bob', 'Carl']</pre>
<p>However, for a list with less than two elements, this will raise an <code>IndexError: pop from empty list</code>. A simple <code>if</code> check can make sure that the list has at least two elements—and otherwise simply override it with the empty list.</p>
<hr class="wp-block-separator has-alpha-channel-opacity"/>
<p>Here’s some background info in case you want to dive deeper into this approach:</p>
<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4a1.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> 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>.</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">
<iframe loading="lazy" title="Python List pop()" width="780" height="439" src="https://www.youtube.com/embed/r9VhOWN5oEg?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
</figure>
<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f30e.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Learn More</strong>: <a href="https://blog.finxter.com/python-list-pop/" data-type="post" data-id="6853" target="_blank" rel="noreferrer noopener">The Python <code>list.pop()</code> method</a></p>
<h2>Summary</h2>
<p>You’ve learned the three easy ways to remove both the first and last elements from a Python list:</p>
<ul>
<li><strong>Method 1</strong>: Slicing <code>list[1:-1]</code></li>
<li><strong>Method 2</strong>: Slicing List Without Negative Index <code>list[1:len(list)-1]</code></li>
<li><strong>Method 3</strong>: <code>list.pop()</code> and <code>list.pop(0)</code></li>
</ul>
<p>Thanks for your interest in learning with Finxter! You can check out our <a href="https://blog.finxter.com/email-academy/" data-type="page" data-id="12278" target="_blank" rel="noreferrer noopener">free email academy</a> here:</p>
<hr class="wp-block-separator has-alpha-channel-opacity"/>
</div>


https://www.sickgaming.net/blog/2022/07/...om-a-list/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016