Python - How To Get Last Element of List in Python

ID : 296

viewed : 115

Tags : PythonPython List

vote vote

92

In this tutorial, we will discuss methods to get the last element of a list in Python.

Get the Last Element of a List With pop() Function in Python

The can be used to get the last element of a list. The pop() function by default returns the last element of the list and removes that element from the list. The following code example shows us how we can get the last element of a list with the pop() function in Python.

list1 = [0,1,2,3,4]  last = list1.pop()  print(last) print(list1) 

Output:

4 [0, 1, 2, 3] 

In the above code, we first initialize a list list1 and then get the last element of the list1 with the pop() function.

Get the Last Element of a List With -1 Index in Python

If we do not want to remove the last element from the list, we have to use -1 as the list index. In Python, the -1 index means the last index. Similarly, the -2 index indicates the second last index and so on. The following code example shows us how we can get the last element of a list with the -1 index in Python.

list1 = [0,1,2,3,4]  print(list1[-1]) print(list1) 

Output:

4 [0, 1, 2, 3, 4] 

In the above code, we first initialize a list list1 and then get the last element of the list1 with the -1 index.

Both methods are doing the same thing, and the only difference is that the pop() function deletes the last element while the -1 index does not.

  • Related HOW TO?