How do I get the last element of a list?
This question explores simple and effective ways to access the final item in a list, including using negative indexing and built-in functions for safe and readable code.
Getting the last element of a list in Python is super easy and one of the most common tasks you’ll encounter. Python offers a few simple ways to do this, depending on your needs.
1. Using Negative Indexing
Python supports negative indexing, which lets you count from the end of the list:
my_list = [10, 20, 30, 40]
last_item = my_list[-1]
print(last_item) # Output: 40
- -1 always refers to the last item.
- -2 would give you the second-last item, and so on.
2. Using len() Function (Less common)
You can also use the len() function to get the last item manually:
last_item = my_list[len(my_list) - 1]
This is more verbose and rarely needed, but useful if you're doing calculations with indices.
3. Using Slicing (Returns a list)
If you want the last n elements, slicing is your friend:
last_element = my_list[-1:] # Returns [40]
Be Careful with Empty Lists
If the list is empty, accessing my_list[-1] will throw an IndexError. You can avoid that with a check:
if my_list:
print(my_list[-1])
else:
print("List is empty")