Python: Get Last Element in List - Stack Abuse

Python: Get Last Element in List

Introduction

In this tutorial, we'll take a look at some of the most common ways to find the last element in a list in Python. First, we will cover the simplest and most Pythonic way and then show some other alternative solutions afterward.

Let's take a look at the list that we will be using:

exampleList = [1, 2, "Three", ["Four", 5], 6]

Note: A list in Python is a collection of elements that are not necessarily the same type. One list can contain elements that are numbers, strings, nested lists, etc.

How to Get the Last Element in a Python List

There's several ways we can go about getting the last element of a list in Python - some of which are more intuitive and practical than others, and some of which actually change the original list in-place:

Winner Solution - Using Negative Indexing

Python supports the notion of negative indexing as the method of accessing list elements. This means that we can access elements in the reversed order by using the [] operator.

It's well known how indexing in lists works:

firstElement = exampleList[0]
nthElement = exampleList[n-1]
...

The first element has the index of 0, the second has the index of 1, and the nth element has an index of n-1.

The negative indexing follows the same logic, but in reversed order. The last element has the index of -1, the second to last element has the index of -2, and so on:

lastElement = exampleList[-1]
print("Last element: ", lastElement)

print("exampleList: ", exampleList)

secondToLast = exampleList[-2]
print("Second to last element: ", secondToLast)

Which outputs:

Last element:  6
exampleList:  [1, 2, 'Three', ['Four', 5], 6]
Second to last element:  ['Four', 5]

Negative indexing does not change the original list. It is only a way of accessing elements without any changes to the original list.

This is by far the simplest and most Pythonic solution, favored by most.

Using Indexing

Simple indexing is usually used to access elements in a list in the original order using the [] operator. As described above, the first element has an index of 0, the second element has an index of 1, and so on. Knowing that, we can conclude that the last element has the index of len(exampleList)-1:

lastElement = exampleList[len(exampleList)-1]
print("Last element: ", lastElement)

print("exampleList: ", exampleList)

secondToLast = exampleList[len(exampleList)-2]
print("Second to last element: ", secondToLast)

Which outputs:

Last element:  6
exampleList:  [1, 2, 'Three', ['Four', 5], 6]
Second to last element:  ['Four', 5]

As well as negative indexing, the indexing method is only used to access elements of the list without performing any changes to the original list.

Using the pop() Method

In Python, the pop() method is used to remove the last element of the given list and return the removed item.

The pop() method can optionally accept an integer argument. It is the index of the element that we want to remove, so if we call exampleList.pop(0), the first element will be removed and returned.

If the argument is the negative number, the logic of the negative indexing will be performed to determine which element to remove. Calling exampleList.pop(-1) will result in removing the last element of the examleList.

Though, since the pop() method by default already pops the last element, there's no real need to use indexing at all:

lastElement = exampleList.pop()
print("Last element: ", lastElement)

print("exampleList: ", exampleList)

Which outputs:

Last element:  6
exampleList:  [1, 2, 'Three', ['Four', 5]]

Note that the pop() method, by definition, does change the original list by removing the popped element.

Using Slicing

In Python, the slicing notation is used to get a sublist of a list. The notation itself is pretty simple:

exampleList[startIndex:[endIndex[:indexStep]]]

This means that we can get the sublist of the exampleList with indices starting from startIndex, all the way to the endIndex with the step of indexStep.

The endIndex and indexStep are optional arguments. If we leave the endIndex blank, its' default value is the end of the original list. The default value for indexStep is 1.

If we have a list l=['a', 'b', 'c', 'd', 'e'] and slice it using l[1:3] the resulting sublist will be ['b', 'c', 'd']. This means that we are choosing elements of the lits l with indices 1, 2, and 3.

l[0:4:2] will return a sublist containing only elements on the even indices - 0, 2, 4.

The key feature of the slicing notation that we will be using is that it supports negative indexing.

Better understand your data with visualizations.

  •  30-day no-questions money-back guarantee
  •  Beginner to Advanced
  •  Updated regularly (latest update June 2021)
  •  Updated with bonus resources and guides

This means that l[-1:] can be interpreted as: get all elements in list l, from the last element to the end of list l. The resulting sublist will contain only the last element of the original list:

lastElement = exampleList[-1:][0]
# exampleList[-1:] alone will return the sublist - [6]
# exampleList[-1:][0] will return the last element - 6
print("Last element: ", lastElement)

print("exampleList: ", exampleList)

Which outputs:

Last element:  6
exampleList:  [1, 2, 'Three', ['Four', 5], 6]

The slicing method is only used to access elements of the list and to create a new list using them - without performing any changes to the original list.

Using the Reverse Iterator

Python has two built-in functions that we will use in this method - reversed() and next().

reversed() accepts a list as an argument and returns the reversed iterator for that list, meaning that the iteration is reversed, starting from the last element all the way to the first element. next() accepts an iterator and returns the next element from the iterator:

reversedIterator = reversed(exampleList)

lastElement = next(reversedIterator)
print("Last element: ", lastElement)

Which outputs:

Last element:  6
exampleList:  [1, 2, 'Three', ['Four', 5], 6]

The reversed iterator method is only used to access elements of the list in reverse order - without performing any changes to the original list.

Using the reverse() Method

The reverse() method is used to reverse the elements of the list. It does not take any arguments and does not return any value, instead, it reverses the original list in-place. This means that we can reverse the list and access the new first element:

# Update the original list by reversing its' elements
exampleList.reverse()

# Access the first element of the updated list
lastElement = exampleList[0]
print("Last element: ", lastElement)

print("exampleList: ", exampleList)

Which outputs:

Last element:  6
exampleList:  [6, ['Four', 5], 'Three', 2, 1]

The reverse() method, by definition, does change the original list by reversing the order of its' elements. Please keep in mind that this approach may be a really inefficient overkill - since it takes time to reverse a list.

Using itemgetter()

The operator module provides a lot of efficient methods performing all of the fundamental operations in Python, such as the mathematical and logical operations, as well as other object comparison and sequence operations.

The itemgetter() method is one of the many methods in the operator module. It accepts one or more integers as the argument and returns a callable object which can be seen as a type of special function.

When we call operator.itemgetter(0), the resulting object will be a function that will gets the first element in a collection. We can also assign a name to that object:

getFirstElement = operator.itemgetter(0)

Now, we can pass in a list to getFirstElement(l), which returns the first element from the list l.

The itemgetter() operator supports negative indexing so retrieving the last element boils down to:

import operator

getLastElement = operator.itemgetter(-1)
lastElement = getLastElement(exampleList)
print("Last element: ", lastElement)

print("exampleList: ", exampleList)

Which outputs:

Last element:  6
exampleList:  [1, 2, 'Three', ['Four', 5], 6]

This approach doesn't modify the original list - it generates a callable object that accesses it using indices.

Using Loops

Now, a much more manual and rudimentary approach would be using loops. We can iterate through the list, using the length of the list as the final step. Then, when on the len(l)-1 step - we can simply return that item:

for i in range(0, len(exampleList)):
    if i == (len(exampleList)-1) : lastElement = exampleList[i]
        
print("Last element: ", lastElement)
print("exampleList: ", exampleList)

Which outputs:

Last element:  6
exampleList:  [1, 2, 'Three', ['Four', 5], 6]

This also doesn't change the list at all and simply accesses an element.

Conclusion

There are a lot of ways to get the last element in a list in Python. The main concern when choosing the right way for you is weather or not you want the last element to be removed.

If you need to get the last element without performing any changes to the original list, then the negative indexing method is the clear winner. It is the simplest and most Pythonic way to solve this problem.

On the other hand, if you need to remove the last element, as well as access it, then you should probably go with the pop() method, which is the built-in method for performing exactly this behavior.

Last Updated: May 5th, 2021

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Want a remote job?

    Prepping for an interview?

    • Improve your skills by solving one coding problem every day
    • Get the solutions the next morning via email
    • Practice on actual problems asked by top companies, like:
     
     
     

    © 2013-2021 Stack Abuse. All rights reserved.