How to Get Last Element of List in Python: Simple Guide
To get the last element of a list in Python, use
list[-1]. This accesses the element at the last position by counting backwards from the end of the list.Syntax
Use list[-1] to get the last element of a list. The -1 index means counting from the end backwards by one position.
list: your list variable[-1]: index for the last element
python
my_list = [10, 20, 30, 40] last_element = my_list[-1] print(last_element)
Output
40
Example
This example shows how to get the last element from a list of numbers and print it.
python
fruits = ['apple', 'banana', 'cherry', 'date'] last_fruit = fruits[-1] print('Last fruit:', last_fruit)
Output
Last fruit: date
Common Pitfalls
Trying to get the last element from an empty list causes an error. Also, using positive indexes like list[len(list)] will cause an IndexError because list indexes start at 0.
Correct way:
- Use
list[-1]for last element - Check if list is not empty before accessing
python
empty_list = [] # Wrong: will cause IndexError # print(empty_list[len(empty_list)]) # Right: check before access if empty_list: print(empty_list[-1]) else: print('List is empty')
Output
List is empty
Quick Reference
Summary tips to get the last element of a list:
- Use
list[-1]to get the last item. - Always check if the list is not empty to avoid errors.
- Negative indexes count from the end, starting at -1.
Key Takeaways
Use
list[-1] to access the last element of a list in Python.Negative indexes count backwards from the end of the list, with -1 as the last item.
Always check if the list is not empty before accessing the last element to avoid errors.
Avoid using positive indexes equal to the list length as it causes IndexError.