We iterate through the list except the last element and we check if all these elements are smaller than the last element.
print all(num < my_list[-1] for num in my_list[:-1])
In Python, the last element can be accessed with the negative indexing. So my_list[-1]
refers to the last element and my_list[-2]
refers to the last but one, etc.
Also we use slicing notation to exclude the last element from the list, with my_list[:-1]
.
Note: The advantage of this method is that, it short circuits immediately after finding a failure. So, we don't have to process the entire list always. In the best case, it returns after processing the first element. This is very useful if the list being processed is very big.
As Ashwini Chaudhary points out in the comments, this is the optimal way to do this
from itertools import islice
print all(num < my_list[-1] for num in islice(my_list, len(my_list) - 1))