In Python, you can get the last element of a list by accessing the last index (-1), for example, in the following way:
my_list = [1, 2, 3, 4]
print(my_list[-1]) # 4
However, for empty lists this will raise an exception:
my_list = []
# IndexError: list index out of range
print(my_list[-1])
You can handle this "IndexError" in several ways; some of which are as follows:
my_list = []
last_idx = my_list[-1] if my_list else "default"
print(last_idx) # "default"
The example above uses a conditional expression (if/else) to handle the case of an empty list and assign a default value.
Alternatively, you can use a try/except block to catch the IndexError and assign a default value in case the list is empty:
my_list = []
try:
last_idx = my_list[-1]
except IndexError:
last_idx = "default"
print(last_idx) # "default"
This approach does not modify the original list. However, it is possible to remove the last element from the list and then return it.