How do I get the last element of a list?

To get the last element of a list, you can use negative indexing. The index -1 refers to the last element, -2 refers to the second last element, and so on.

Here's an example:

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

# Get the last element
last_element = my_list[-1]

print(last_element)  # Output: 5

Watch a course Python - The Practical Guide

You can also use the len() function to get the last element of a list. The len() function returns the number of elements in a list, so you can use it to get the index of the last element.

Here's an example:

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

# Get the index of the last element
last_index = len(my_list) - 1

# Get the last element
last_element = my_list[last_index]

print(last_element)  # Output: 5