- 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:
- Accessing the last element in a list in Python
- 5 Answers 5
- Related
- Hot Network Questions
- Subscribe to RSS
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:
Accessing the last element in a list in Python
I have a list for example: list_a = [0,1,3,1] and I am trying to iterate through each number this loop, and if it hits the last «1» in the list, print «this is the last number in the list» since there are two 1’s, what is a way to access the last 1 in the list? I tried:
if list_a[-1] == 1: print "this is the last" else: # not the last
if list_a.index(3) == list_a[i] is True: print "this is the last"
The thing is, in Python, you just can’t distinguish between those two 1, they are the same object and both list positions point to the same object.
How did your first solution not work? I surely print out this is the last . Should it print this sentence if the last number is 1? If so, it works.
5 Answers 5
list_a[-1] is the way to access the last element
@F.C. The questions says that comparing the last element to 1 didn’t work: list_a[-1] == 1 , which is not the same thing as this answer.
@F.C. Come on Man! You know that in lists list_a[-1] always refers to the last element. The OP is confused on this as there are two elements with the same value in the list. This does not mean that list_a[-1] is wrong. Just that we need to re-affirm to the OP saying that he should not be confused and that list_a[-1] is the correct way to access the last element
@GodMan ok, maybe you should add some explanation to your answer, I don’t think it would help much as it is.
You can use enumerate to iterate through both the items in the list, and the indices of those items.
for idx, item in enumerate(list_a): if idx == len(list_a) - 1: print item, "is the last" else: print item, "is not the last"
0 is not the last 1 is not the last 3 is not the last 1 is the last
Tested on Python 2.7.3
This solution will work for any sized list.
^We count the number of elements in the list and subtract 1. This is the coordinate of the last element.
print "The last variable in this list is", list_a[last]
^We display the information.
a = [1, 2, 3, 4, 1, 'not a number'] index_of_last_number = 0 for index, item in enumerate(a): if type(item) == type(2): index_of_last_number = index
The output is 4, the index in array a of the last integer. If you want to include types other than integers, you can change the type(2) to type(2.2) or something.
To be absolutely sure you find the last instance of «1» you have to look at all the items in the list. There is a possibility that the last «1» will not be the last item in the list. So, you have to look through the list, and remember the index of the last one found, then you can use this index.
list_a = [2, 1, 3, 4, 1, 5, 6] lastIndex = 0 for index, item in enumerate(list_a): if item == 1: lastIndex = index print lastIndex
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.27.43548
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.