In this tutorial, learn how to find last element of list with Python. The short answer is: use the index operator() with -1 as the index value. You will get the last element of the list with simple methods given here.
While coding in Python, you may want to get the last element to use on your project. There are two methods you can use to get the last element of the list. The first method uses the index operator while the second method using the
pop(). The former gives only the last element, but the latter also deletes the last element.
Find Last Element of List in Python
If you want to find the last element of the given list, you can use the Python index operator(). There is one value as the argument of the index operator to pass. The value with the index operator is
[-1], which you have to use to get the output as the last element of the list.
See the example below to get the idea of how to get the last element from Python list.
myList = ["Bill", 18, "Smith", "Dara", 21, "Wilson"];
The above example, contains 6 list elements, including the string and integers. The output contains the last element of the list which is “Wilson”.
Get and Remove the Final Item of List Using Python
You can also get the last element of the list using the
pop(). To use the pop function and find the last element of the list, you have to use the below given method.
In addition to finding the last element of the list, the pop ()
also deletes the last element from the Python list. After the execution of the pop function, you will get elements of the list without the previous last element.
myList = ["John", 17, "Sam", "Kevin",53, "Maven"];
[“John”, 17, “Sam”, “Kevin”,53]
The above example contains the last element in the output. It also contains the list elements after execution of the pop function. Previously, the list contains 6 elements, but after execution of the pop(). There are only 5 elements remaining in the Python list.
You may also like to read
- Find First And Last Element Of Tuple In Python
- Get Element of the List By Index In Python
- How to Find the Index of the Tuple Element In Python
Hope, you like this post of how to find the last element of the list in Python. If you have any query regarding the tutorial, please comment below.
Also tell me, which method you are using to get last element from your list in Python.