Get last element of list Python

In this tutorial, let us look at the most efficient ways to find the last element in list in Python.

What is a List in Python?

The list is one of the most commonly used data types in Python. A list is a collection of elements that can be of any data type. A single list can contain a combination of numbers, strings, nested lists, etc.

How to Get the Last Element of a List in Python

Method 1 – By Iterating all the elements in a list

The most common and straightforward way to get last element in list is through iterating the entire element till it reaches the last element, as shown below.

# Python code to access the last element # in a list using for loop # Declaring and initializing list number_list = [2, 1, 7, 4, 5, 3,6] print ["List of elements are : " + str[number_list]] # using loop method to print last element for i in range[0, len[number_list]]: if i == [len[number_list]-1]: print ["The last element of list is : "+ str[number_list[i]]] # Output List of elements are : [2, 1, 7, 4, 5, 3, 6] The last element of list is : 6

Method 2 – Using the reverse[] method

The reverse[] method in Python is used to reverse the elements of a list. The reverse[] method does not take any arguments and does not return any values instead, it reverses the existing list.

# Python code to access the last element # in a list using reverse[] method # Declaring and initializing list number_list = [2, 1, 7, 4, 5, 3,6] print ["List of elements are : " + str[number_list]] # using reverse method to print last element number_list.reverse[] print["The last element of list using reverse method are : " + str[number_list[0]]] # Output List of elements are : [2, 1, 7, 4, 5, 3, 6] The last element of list using reverse method are : 6

Method 3 – Using pop[] method

The pop[] method is used to access the last element of the list and returns the removed item. The pop[] method accepts an integer as the argument, which is basically the index of the item which needs to be removed from the list.

Example – list.pop[0] will remove and return the first element in the list. 

Note – Calling the pop[] method will remove the last item from the list itself. Hence if you are re-using the list, this approach is not recommended as the element is removed.

# Python code to access the last element # in a list using pop[] method # Declaring and initializing list number_list = [2, 1, 7, 4, 5, 3,6] print ["List of elements are : " + str[number_list]] # using pop[] method to print last element print["The last element of list using reverse method are : " + str[number_list.pop[]]] # Output List of elements are : [2, 1, 7, 4, 5, 3, 6] The last element of list using reverse method are : 6

Method 4 – Using Negative Indexing [] Operator

The negative index is the way of indexing the element from the end of the list with an index starting from -1, i.e., -1 gives the last element, -2 gives the last 2nd element, and so on.

The major use of negative indexing can be used to reverse a list without using any built-in function. 

You can also find the last element in the list using length-1. In order to access the last element, we need to know the length of the list.

# Python code to access the last element # in a list using negative indexing # Declaring and initializing list number_list = [2, 1, 7, 4, 5, 3,6] print ["List of elements are : " + str[number_list]] # using length-1 to print last element print["The last element of list using length-1 method are : " + str[number_list[len[number_list] -1]]] # using [] operator to print last element print["The last element of list using reverse method are : " + str[number_list[-1]]] # Output List of elements are : [2, 1, 7, 4, 5, 3, 6] The last element of list using length-1 method are : 6 The last element of list using reverse method are : 6

Method 5 – Using itemgetter[] 

The operator module in Python has vast features to perform all mathematical, logical, comparison operations.

The itemgetter[] method is one of the methods in the operator module, and it accepts one or more integer arguments and returns the callable object.

import operator # Python code to access the last element # in a list using itemgetter[] method # Declaring and initializing list number_list = [2, 1, 7, 4, 5, 3,6] print ["List of elements are : " + str[number_list]] getLastElement = operator.itemgetter[-1] # using [] operator to print last element print["The last element of list using reverse method are : " + str[getLastElement[number_list]]] # Output List of elements are : [2, 1, 7, 4, 5, 3, 6] The last element of list using reverse method are : 6

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.

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:

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

lastElement = exampleList[-1:][0] 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:

exampleList.reverse[] 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.

Video liên quan

Chủ Đề