- 6 ways to get the last element of a list in Python
- Get last item of a list using negative indexing
- Frequently Asked:
- Get last item of a list using list.pop()
- Get last item of a list by slicing
- Get last item of a list using itemgetter
- Get last item of a list through Reverse Iterator
- Get last item of a list by indexing
- Related posts:
- Python: How to Get the Last Item (or Last n Items) From a List
- How Does List Indexing Work in Python?
- Python: Get the Last Item from a List Using Negative Indexing
- Get the Last n Items from a List Using Negative Indexing
- PyTorch Tutorial: Develop Deep Learning Models with Python
- How to Get the Last Item From a Python List and Remove It
6 ways to get the last element of a list in Python
In this article, we will discuss six different ways to get the last element of a list in python.
Get last item of a list using negative indexing
List in python supports negative indexing. So, if we have a list of size “S”, then to access the Nth element from last we can use the index “-N”. Let’s understand by an example,
Suppose we have a list of size 10,
sample_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
To access the last element i.e. element at index 9 we can use the index -1,
# Get last element by accessing element at index -1 last_elem = sample_list[-1] print('Last Element: ', last_elem)
Similarly, to access the second last element i.e. at index 8 we can use the index -2.
Frequently Asked:
Using negative indexing, you can select elements from the end of list, it is a very efficient solution even if you list is of very large size. Also, this is the most simplest and most used solution to get the last element of list. Let’s discuss some other ways,
Get last item of a list using list.pop()
In python, list class provides a function pop(),
It accepts an optional argument i.e. an index position and removes the item at the given index position and returns that. Whereas, if no argument is provided in the pop() function, then the default value of index is considered as -1. It means if the pop() function is called without any argument then it removes the last item of list and returns that.
Let’s use this to remove and get the last item of the list,
sample_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] # Remove and returns the last item of list last_elem = sample_list.pop() print('Last Element: ', last_elem)
The main difference between this approach and previous one is that, in addition to returning the last element of list, it also removes that from the list.
Get last item of a list by slicing
We can slice the end of list and then select first item from it,
sample_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] # Get a Slice of list, that contains only last item and select that item last_elem = sample_list[-1:][0] print('Last Element: ', last_elem)
We created a slice of list that contains only the last item of list and then we selected the first item from that sliced list. It gives us the last item of list. Although it is the most inefficient approach, it is always good to know different options.
Get last item of a list using itemgetter
Python’s operator module provides a function,
It returns a callable object that fetches items from its operand using the operand’s __getitem__() method. Let’s use this to get the last item of list by passing list as an operand and index position -1 as item to be fetched.
import operator sample_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] last_elem = operator.itemgetter(-1)(sample_list) print('Last Element: ', last_elem)
It gives us the last item of list.
Get last item of a list through Reverse Iterator
In this solution we are going to use two built-in functions,
- reversed() function : It accepts a sequence and returns a Reverse Iterator of that sequence.
- next() function: It accepts an iterator and returns the next item from the iterator.
So, let’s use both the reversed() and next() function to get the last item of a list,
sample_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] # get Reverse Iterator and fetch first element from reverse direction last_elem = next(reversed(sample_list), None) print('Last Element: ', last_elem)
It gives us the last item of list.
How did it work?
By calling the reversed() function we got a Reverse Iterator and then we passed this Reverse Iterator to the next() function. Which returned the next item from the iterator.
As it was a Reverse Iterator of our list sequence, so it returned the first item in reverse order i.e. last element of the list.
Get last item of a list by indexing
As the indexing in a list starts from 0th index. So, if our list is of size S, then we can get the last element of list by selecting item at index position S-1.
Let’s understand this by an example,
sample_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] # get element at index position size-1 last_elem = sample_list[len(sample_list) - 1] print('Last Element: ', last_elem)
It gives us the last item of list.
Using the len() function we got the size of the list and then by selecting the item at index position size-1, we fetched the last item of the list.
So, here we discussed 6 different ways to fetch the last element of a list, although first solution is the simplest, efficient and most used solution. But it is always good to know other options, it gives you exposure to different features of language. It might be possible that in future, you might encounter any situation where you need to use something else, like in 2nd example we deleted the last element too after fetching its value.
The Complete example is as follows,
import operator def main(): print('*** Get last item of a list using negative indexing ***') sample_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] # Get last element by accessing element at index -1 last_elem = sample_list[-1] print('Last Element: ', last_elem) print('*** Get last item of a list using list.pop() ***') sample_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] # Remove and returns the last item of list last_elem = sample_list.pop() print('Last Element: ', last_elem) print('*** Get last item of a list by slicing ***') sample_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] last_elem = sample_list[-1:][0] print('Last Element: ', last_elem) print('*** Get last item of a list using itemgetter ***') sample_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] last_elem = operator.itemgetter(-1)(sample_list) print('Last Element: ', last_elem) print('*** Get last item of a list through Reverse Iterator ***') sample_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] # get Reverse Iterator and fetch first element from reverse direction last_elem = next(reversed(sample_list), None) print('Last Element: ', last_elem) print("*** Get last item of a list by indexing ***") sample_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] # get element at index position size-1 last_elem = sample_list[len(sample_list) - 1] print('Last Element: ', last_elem) if __name__ == '__main__': main()
*** Get last item of a list using negative indexing *** Last Element: 9 *** Get last item of a list using list.pop() *** Last Element: 9 *** Get last item of a list by slicing *** Last Element: 9 *** Get last item of a list using itemgetter *** Last Element: 9 *** Get last item of a list through Reverse Iterator *** Last Element: 9 *** Get last item of a list by indexing *** Last Element: 9
Related posts:
Python: How to Get the Last Item (or Last n Items) From a List
In this post, you’ll learn how to use Python to get the last item from a list as well how as how to get the last n items from a list. You’ll learn a total of 4 different ways to accomplish this, learning how to find the best method for your unique solution. Let’s get started!
The Quick Answer: Use Negative Indexing
How Does List Indexing Work in Python?
One of the unique attributes of Python lists is that they are ordered, meaning that their order matters. Because of this, we can access list items by their index positions.
Python lists begin at the 0th index, meaning that to get the first item, you would access index #0. Because of this, if you know how long a list is, you can access its last item by accessing that specific index. Say we have a list of length n, you would access the (n-1)th index.
This, of course, isn’t always practical because you don’t always know how long a list really is. Because of this, you can also access the list from the end, using negative indexing. By accessing the index of -1 , you would be accessing the last item in that list.
See the graphic below for an example of how indexes appear in a list:
Now that you have an understanding of how list indexing works in Python, let’s get started to access the last item in a list.
Python: Get the Last Item from a List Using Negative Indexing
Getting the last item in a Python list using negative indexing is very easy. We simply pull the item at the index of -1 to get the last item in a list.
Let’s see how this works in practice:
a_list = ['datagy', 1,[3,4,5], 14.3, 32, 3] last_item = a_list[-1] print(last_item) #Returns: 3
Similarly, if you wanted to get the second last item, you could use the index of -2 , as shown below:
a_list = ['datagy', 1,[3,4,5], 14.3, 32, 3] second_last_item = a_list[-2] print(second_last_item) #Returns: 32
Now let’s see how to get multiple items, specifically the last n items, from a list using negative indexing.
Get the Last n Items from a List Using Negative Indexing
In the section above, you learned how to use Python to get the last item from a list. Now, you’ll learn how to get the last n items from a Python list.
Similar to the approach above, you’ll use negative indexing to access the last number of items.
One thing that’s great about Python is that if you want your indexing to go to the end of a list, you simply do not include a number at the end of the index.
Let’s say we wanted to return the last 2 items, we could write the following code:
a_list = ['datagy', 1,[3,4,5], 14.3, 32, 3] items = a_list[-2:] print(items) #Returns: [32, 3]
Similar to the example above, we could have have written our index to be [-2:-1] . However, omitting the -1 simply indicates that we want our index to go to the end of the list.
Interestingly, when slicing multiple items, even when they don’t exist, the whole list will be returned. For example, we shown below that slicing from the item -10 to the end doesn’t raise an error, but it also just omits the items that don’t exist.
a_list = ['datagy', 1,[3,4,5], 14.3, 32, 3] items = a_list[-10:] print(items) #Returns: ['datagy', 1, [3, 4, 5], 14.3, 32, 3]
In the next section, you’ll learn how to get the last item form a Python list and remove it.
PyTorch Tutorial: Develop Deep Learning Models with Python
In this tutorial, you’ll learn how to use PyTorch for an end-to-end deep learning project. Learning PyTorch can seem intimidating, with its specialized classes and workflows – but it doesn’t have to be. This tutorial will abstract away the math behind neural networks and deep learning. Instead, we’ll focus on learning the mechanics behind how… Read More » PyTorch Tutorial: Develop Deep Learning Models with Python
How to Get the Last Item From a Python List and Remove It
Python has a built-in method, the .pop() method, that let’s you use Python to get the last item from a list and remove it from that list. This can be helpful for many different items, such as game development and more.
Let’s take a look at how we can make this happen in practise:
a_list = ['datagy', 1,[3,4,5], 14.3, 32, 3] last_item = a_list.pop() print(f'') print(f'') # Returns: # a_list=['datagy', 1, [3, 4, 5], 14.3, 32] # last_item=3
You can see here that when we print out the list following applying the .pop() method, that the last item has been removed. Furthermore, it has been assigned to the variable last_item .
Tip! We’ve used some f-string formatting here to print out both the variable name and the variable contents simultaneously. Learn more about how to do this in my tutorial here (requires Python 3.8+).