What is the easiest way to access the last element of a list?


#1

Question

Is there a way to find the last item in a list without using the len() function?

Answer

The last item in a list can be found using the index value computed by len() - 1 for the list. A short-hand for this is to use an index value of -1. For any list, accessing the index of [-1] will return the last element of the list without needing to use the len() function.

In the example below, both print() functions will output orange for the color.

colors = ['red', 'green', 'blue', 'yellow', 'orange']

print(colors[-1])

print(colors[len(colors) - 1])