[Tut] How to Get the Last Element of a Python List? - Printable Version +- Sick Gaming (https://www.sickgaming.net) +-- Forum: Programming (https://www.sickgaming.net/forum-76.html) +--- Forum: Python (https://www.sickgaming.net/forum-83.html) +--- Thread: [Tut] How to Get the Last Element of a Python List? (/thread-97472.html) |
[Tut] How to Get the Last Element of a Python List? - xSicKxBot - 09-27-2020 How to Get the Last Element of a Python List? <div><p><strong>Problem</strong>: Given a <a href="https://blog.finxter.com/python-lists/" target="_blank" rel="noreferrer noopener" title="The Ultimate Guide to Python Lists">list</a>. How to access the last element of this list?</p> <p><strong>Example</strong>: You have the list <code>['Alice', 'Bob', 'Liz']</code> and you want to get the last element <code>'Liz'</code>. </p> <p><strong>Quick solution</strong>: Use negative <a href="https://blog.finxter.com/daily-python-puzzle-list-indexing/" target="_blank" rel="noreferrer noopener" title="List Indexing">indexing </a>-1.</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="">friends = ['Alice', 'Bob', 'Liz'] print(friends[-1]) # Liz</pre> <p class="has-pale-cyan-blue-background-color has-background">To access the last element of a Python list, use the indexing notation <code>list[-1]</code> with negative index <code>-1</code> which points to the last list element. To access the second-, third-, and fourth-last elements, use the indices <code>-2</code>, <code>-3</code>, and <code>-4</code>. To access the <code>n</code> last elements of a list, use slicing <code>list[:-n-1:-1]</code> with negative stop index <code>-n</code> and negative step size <code>-1</code>. </p> <h2>Method 1: Access the Last Element with Negative Indexing -1</h2> <p>To bring everybody on the same page, let me quickly explain indices in Python by example. Suppose, you have list <code>['u', 'n', 'i', 'v', 'e', 'r', 's', 'e']</code>. The indices are simply the positions of the characters of this string.</p> <figure class="wp-block-table is-style-stripes"> <table> <tbody> <tr> <td><strong>(Positive) Index</strong></td> <td>0</td> <td>1</td> <td>2</td> <td>3</td> <td>4</td> <td>5</td> <td>6</td> <td>7</td> </tr> <tr> <td><strong>Element</strong></td> <td>‘u’</td> <td>‘n’</td> <td>‘i’</td> <td>‘v’</td> <td>‘e’</td> <td>‘r’</td> <td>‘s’</td> <td>‘e’</td> </tr> <tr> <td><strong>Negative Index</strong></td> <td>-8</td> <td>-7</td> <td>-6</td> <td>-5</td> <td>-4</td> <td>-3</td> <td>-2</td> <td>-1</td> </tr> </tbody> </table> </figure> <p><strong>Positive Index</strong>: The first character has index <code>0</code>, the second character has index <code>1</code>, and the <code>i</code>-th character has index <code>i-1</code>.</p> <p><strong>Negative Index</strong>: The last character has index <code>-1</code>, the second last character has index <code>-2</code>, and the <code>i</code>-th last character has index <code>-i</code>.</p> <p>Now, you can understand how to access the last element 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="">friends = ['Alice', 'Bob', 'Liz'] print(friends[-1]) # Liz</pre> <p>But how to access the second-last element? Just use index -2!</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="">friends = ['Alice', 'Bob', 'Liz'] print(friends[-2]) # Bob</pre> <h2>Method 2: Access the n Last Elements with Slicing</h2> <p>But what if you want to access the <code>n</code> last elements? The answer is <a href="https://blog.finxter.com/introduction-to-slicing-in-python/" title="Introduction to Slicing in Python" target="_blank" rel="noreferrer noopener">slicing</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> <p>The default slicing operation <code>list[start:stop:step]</code> accesses all elements between <code>start</code> (included) and <code>stop</code> (excluded) indices, using the given <code>step</code> size over the list. For example, the slicing operation <code>friends[0:3:2]</code> would start with the first element <code>'Alice'</code> and end with the third element <code>'Liz'</code> (included), but taking only every second element due to the step size of <code>2</code>—effectively skipping the second element <code>'Bob'</code>. </p> <p>You can use slicing with negative <code>start</code> and <code>stop</code> indices and with negative stop size to slice from the right to the left. To access the <code>n</code> last elements in the slice, you’d therefore use the following 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="">universe = ['u', 'n', 'i', 'v', 'e', 'r', 's', 'e'] # Access the n=4 last element from the list: n = 4 print(universe[:-n-1:-1]) # ['e', 's', 'r', 'e']</pre> <p>There are different points to consider in the code:</p> <ul> <li>You use a negative step size -1 which means that you slice from the right to the left.</li> <li>If you don’t provide a value for <code>start</code>, <code>stop</code>, or <code>step</code> indices, Python takes the default ones. For example, we don’t provide the <code>start</code> index and perform negative slicing so Python starts from the last element <code>'e'</code>. </li> <li>You want to get the <code>n</code> last elements. The <code>n</code>-th last element has index <code>-n</code>. But as the stop index is never included in the slice, we need to slice one step further to the left—to the element with index <code>-n-1</code> to include the element with index <code>-n</code>. </li> </ul> <p>Try this yourself in our interactive code shell:</p> <p> <iframe height="400px" width="100%" src="https://repl.it/@finxter/FailingVagueAgents?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>: What happens if the list has less than n characters?</em></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/how-to-get-the-last-element-of-a-python-list/" target="_blank" rel="noopener noreferrer">How to Get the Last Element of a Python List?</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/27/how-to-get-the-last-element-of-a-python-list/ |