List, being an essential python container is used in day-day programming and also in web-development. Knowledge of its operations is necessary.
Let’s see all the different ways of accessing the last element of a list.
Method #1 : Naive Method
There can be 2-naive methods to get the last element of the list.
- Iterating the whole list and getting, the second last element.
- Reversing the list and printing the first element.
The original list is : [1, 4, 5, 6, 3, 5] The last element of list using loop : 5 The last element of list using reverse : 5
Method #2 : Using  operator
The last element can be assessed easily if no. of elements in list are already known. There are 2 index in Python that point to last element in list.
list[ len - 1 ]: Points to last element by definition.
list[-1]: In python, negative indexing starts from end.
The original list is : [1, 4, 5, 6, 3, 5] The last element using [ len -1 ] is : 5 The last element using [ -1 ] is : 5
Method #3 : Using
list.pop() method is used to access the last element of the list. The drawback of this approach is that it also deletes the list last element, hence is only encouraged to use when list is not to be reused.
The original list is : [1, 4, 5, 6, 3, 5] The last element using pop() is : 5
Method #4 : Using
reversed() coupled with
next() can easily be used to get the last element, as like one of the naive method, reversed method returns the reversed ordering of list as an iterator, and
next() method prints the next element, in this case last element.
The original list is : [1, 4, 5, 6, 3, 5] The last element using reversed() + next() is : 5
- Python | Replace elements in second list with index of same element in first list
- Python | Subtract two list elements if element in first list is greater
- Python | Indices list of matching element from other list
- Python | Slicing list from Kth element to last element
- Python | Move one list element to another list
- Python | Three element sum in list
- Python | Every Kth element in list
- Python | Move element to end of the list
- Python | Element repetition in list
- Python | Insert after every Nth element in a list
- Python | Top N pairs by Kth element from list
- Python | Add the element in the list with help of indexing
- Python | Remove given element from the list
- Python | Operation to each element in list
- Python | Equidistant element list
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.