In This tutorial, we will learn How do get the last element of a list there are four ways to do so slicing, using for Loop, using pop, and using negative indexing. So let’s discuss each with an example.
List In Python
There are different ways to get the last element of the list
Using Slicing
Slicing is a way to get elements of a list where we need to provide the index numbers so that it can access the elements to understand in a better way follow the code given below and learn.
inputList = [5, 1, 6, 8, 3] lastElement = inputList[-1:][0] # printing the last element of the list print("Last element of the input list = ", lastElement)
The above code will result in the last element of the list which is 3.
Using Negative Indexing
inputList = [5, 1, 6, 8, 3] # getting the last element of the list using the length of the list - 1 as an index(Here list index starts from 0 so list length -1 gives the index of the last element of the list) print("Last element of the input list using len(list)-1 as index = ", inputList[len(inputList) - 1]) # getting the last element of the list using - 1 as the index print("Last element of the input list using -1 as index = ", inputList[-1])
It will also result in 3.
Using Pop()
We can also use pop in build function for getting the last element
inputList = [5, 1, 6, 8, 3] # getting the last element of the list using pop() method print("Last element of the input list = ", inputList.pop())
Using For Loop
It is a way to iterate the whole list and at last we will get the last element
inputList = [5, 1, 6, 8, 3] for k in range(0, len(inputList)): if k == (len(inputList)-1): print("Last element of the input list = ", inputList[k])
It will also give three as result but it will have the highest complexity of O(n) as it is using a for loop running till the length of the list so it is the least preferred method to be followed.
To learn more about getting the last element of a list visit List and their operations in Python
Also, visit Some Basic Python List Programs-3 to learn more about the list and its operations. Also, visit beta python for programming Solutions to learn more about different programming problems and solve them to learn more.