Python List – Get Last Element

Python List – Get last element

To get the last element of a list in Python, you can use the negative index -1 with the list variable.

The negative index of -1 fetches the first element from the ending of the list. Meaning, it fetches the last element in the list.

In this tutorial, you will learn how to get the last element in a given list using index, with examples.

For example, if my_list is a given list of elements, then the syntax to the expression to get the last element in the list my_list is

my_list[-1]

This expression is equivalent to the following expression, which uses a positive index.

my_list[len(my_list) - 1]

Examples

The following are some of the examples, where we take a list of elements, and get the last element from the list using index.

1. Get the last element in the list of integers in Python

In this example, we take a list of integer values, and get the last element using index -1, and print it to standard output.

Python Program

my_list = [10, 20, 30, 40]
last_element = my_list[-1]
print(f"Last element : {last_element}")
Run Code Copy

Output

Last element : 40

Explanation

10, 20, 30, 40  ← list elements
-4  -3  -2  -1  ← negative index values
             ↑
element at index=-1 is the last element

2. Get the last element in the list of strings in Python

In this example, we take a list of string values, and get the last element using index.

Python Program

my_list = ["apple", "banana", "cherry"]
last_element = my_list[-1]
print(f"Last element : {last_element}")
Run Code Copy

Output

Last element : cherry

Explanation

"apple", "banana", "cherry"  ← list elements
-3       -2        -1        ← negative index values
                    ↑
     element at index=-1 is the last element

Summary

In this Python Lists tutorial, we have seen how to get the last element of the given list using index.

Code copied to clipboard successfully 👍