Write a Python Program to Get the Last Element of the List

Python is a high-level programming language that is widely used in various fields, including data science, web development, and automation.

One of the common tasks in Python programming is to retrieve the last element of a list.

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


Lists are one of the most versatile data structures in Python, which allow us to store a collection of elements in a single variable.

The elements in a list can be of different types, including numbers, strings, or even other lists.

To retrieve the last element of a list, we can use the indexing operator [] and the -1 index.

The -1 index refers to the last element of a list, the -2 index refers to the second last element, and so on.

Here’s a simple Python program that demonstrates how to get the last element of a list:

my_list = [1, 2, 3, 4, 5]
last_element = my_list[-1]
print(last_element)

In this program, we first define a list my_list containing five integer elements.

We then use the indexing operator -1 to retrieve the last element of the list and assign it to the variable last_element.

Finally, we print the value of last_element to the console.

The output of this program will be:

5

If the list is empty, i.e., it does not contain any elements, then trying to access the last element using the -1 index will result in an IndexError.

To avoid this, we can first check if the list is not empty using the len() function, like this:

my_list = []
if len(my_list) > 0:
    last_element = my_list[-1]
    print(last_element)
else:
    print("The list is empty.")

In this program, we first define an empty list my_list.

We then check if the length of my_list is greater than 0 using the len() function.

If the list is not empty, we retrieve the last element using the -1 index and print it to the console.

If the list is empty, we print a message indicating that the list is empty.


In conclusion, getting the last element of a list in Python is a simple task that can be accomplished using the -1 index and the indexing operator [].

It is important to remember to check if the list is not empty before accessing the last element to avoid IndexError.