How to get the last element of list in Python

Published on Aug. 22, 2023, 12:15 p.m.

It looks like you may have accidentally included search results for a different question in your response. Nonetheless, here’s how you can get the last element of a list in Python:

To get the last element of a list in Python, you can use the index -1, which represents the last element of the list. For example:

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

print(last_element) # Output: 5

In this example, we define a list my_list and use the index -1 to get the last element of the list. We then store the result in the variable last_element and print it out to the console.

Note that this method assumes that the list is not empty. If you want to handle the case where the list is empty, you should check the length of the list before accessing the last element to avoid an IndexError.

Tags: