{"id":118576,"date":"2020-09-27T06:19:27","date_gmt":"2020-09-27T06:19:27","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=13819"},"modified":"2020-09-27T06:19:27","modified_gmt":"2020-09-27T06:19:27","slug":"how-to-get-the-last-element-of-a-python-list","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2020\/09\/27\/how-to-get-the-last-element-of-a-python-list\/","title":{"rendered":"How to Get the Last Element of a Python List?"},"content":{"rendered":"<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>\n<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>\n<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>\n<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']\nprint(friends[-1])\n# Liz<\/pre>\n<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>\n<h2>Method 1: Access the Last Element with Negative Indexing -1<\/h2>\n<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>\n<figure class=\"wp-block-table is-style-stripes\">\n<table>\n<tbody>\n<tr>\n<td><strong>(Positive) Index<\/strong><\/td>\n<td>0<\/td>\n<td>1<\/td>\n<td>2<\/td>\n<td>3<\/td>\n<td>4<\/td>\n<td>5<\/td>\n<td>6<\/td>\n<td>7<\/td>\n<\/tr>\n<tr>\n<td><strong>Element<\/strong><\/td>\n<td>&#8216;u&#8217;<\/td>\n<td>&#8216;n&#8217;<\/td>\n<td>&#8216;i&#8217;<\/td>\n<td>&#8216;v&#8217;<\/td>\n<td>&#8216;e&#8217;<\/td>\n<td>&#8216;r&#8217;<\/td>\n<td>&#8216;s&#8217;<\/td>\n<td>&#8216;e&#8217;<\/td>\n<\/tr>\n<tr>\n<td><strong>Negative Index<\/strong><\/td>\n<td>-8<\/td>\n<td>-7<\/td>\n<td>-6<\/td>\n<td>-5<\/td>\n<td>-4<\/td>\n<td>-3<\/td>\n<td>-2<\/td>\n<td>-1<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n<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>\n<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>\n<p>Now, you can understand how to access the last element of the list:<\/p>\n<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']\nprint(friends[-1])\n# Liz<\/pre>\n<p>But how to access the second-last element? Just use index -2!<\/p>\n<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']\nprint(friends[-2])\n# Bob<\/pre>\n<h2>Method 2: Access the n Last Elements with Slicing<\/h2>\n<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>\n<figure class=\"wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio\">\n<div class=\"wp-block-embed__wrapper\">\n<div class=\"ast-oembed-container\"><iframe loading=\"lazy\" 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>\n<\/div>\n<\/figure>\n<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>&#8212;effectively skipping the second element <code>'Bob'<\/code>. <\/p>\n<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&#8217;d therefore use the following code:<\/p>\n<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:\nn = 4\nprint(universe[:-n-1:-1])\n# ['e', 's', 'r', 'e']<\/pre>\n<p>There are different points to consider in the code:<\/p>\n<ul>\n<li>You use a negative step size -1 which means that you slice from the right to the left.<\/li>\n<li>If you don&#8217;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&#8217;t provide the <code>start<\/code> index and perform negative slicing so Python starts from the last element <code>'e'<\/code>. <\/li>\n<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&#8212;to the element with index <code>-n-1<\/code> to include the element with index <code>-n<\/code>. <\/li>\n<\/ul>\n<p>Try this yourself in our interactive code shell:<\/p>\n<p> <iframe loading=\"lazy\" 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>\n<p><em><strong>Exercise<\/strong>: What happens if the list has less than n characters?<\/em><\/p>\n<h2 class=\"wp-block-block\">Where to Go From Here?<\/h2>\n<p>Enough theory, let\u2019s get some practice!<\/p>\n<p>To become successful in coding, you need to get out there and solve real problems for real people. That\u2019s how you can become a six-figure earner easily. And that\u2019s how you polish the skills you really need in practice. After all, what\u2019s the use of learning theory that nobody ever needs?<\/p>\n<p><strong>Practice projects is how you sharpen your saw in coding!<\/strong><\/p>\n<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>\n<p>Then become a Python freelance developer! It\u2019s the best way of approaching the task of improving your Python skills\u2014even if you are a complete beginner.<\/p>\n<p>Join my free webinar <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/webinar-freelancer\/\" target=\"_blank\">\u201cHow to Build Your High-Income Skill Python\u201d<\/a> and watch how I grew my coding business online and how you can, too\u2014from the comfort of your own home.<\/p>\n<p><a href=\"https:\/\/blog.finxter.com\/webinar-freelancer\/\" target=\"_blank\" rel=\"noreferrer noopener\">Join the free webinar now!<\/a><\/p>\n<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>\n","protected":false},"excerpt":{"rendered":"<p>Problem: Given a list. How to access the last element of this list? Example: You have the list [&#8216;Alice&#8217;, &#8216;Bob&#8217;, &#8216;Liz&#8217;] and you want to get the last element &#8216;Liz&#8217;. Quick solution: Use negative indexing -1. friends = [&#8216;Alice&#8217;, &#8216;Bob&#8217;, &#8216;Liz&#8217;] print(friends[-1]) # Liz To access the last element of a Python list, use the [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[857],"tags":[73,468,528],"class_list":["post-118576","post","type-post","status-publish","format-standard","hentry","category-python-tut","tag-programming","tag-python","tag-tutorial"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/118576","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=118576"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/118576\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=118576"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=118576"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=118576"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}