Get Last Element of List in Python

Get Last Element of List in Python

Muhammad Maisam Abbas Nov-26, 2021 Mar-04, 2021 Python Python List
  1. Get the Last Element of a List With pop() Function in Python
  2. Get the Last Element of a List With -1 Index in Python

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 pop() function 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.

Muhammad Maisam Abbas avatar Muhammad Maisam Abbas avatar

Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.

LinkedIn

Related Article - Python List

  • Convert a Dictionary to a List in Python
  • Remove All the Occurrences of an Element From a List in Python
  • Remove Duplicates From List in Python
  • Get the Average of a List in Python
  • What Is the Difference Between List Methods Append and Extend
  • Convert a List to String in Python