Question

I have a list and want to compare if the last value is greater than the past 10 values, however, I know there is a much easier way to approach this then the code below:

list = [1,2,3,4,5,6,7,8,9,10]

if list[-1] > list[-2] and list[-1] > list[-3] and list[-1] > list[-4]:  (etc)
     print "It's bigger"

Any suggestions would be greatly appreciated!

Was it helpful?

Solution

One way is to take the maximum of the past values and compare it with the last:

>>> l = [1,2,3,4,5,6,7,8,9,10]
>>> if l[-1] > max(l[:-1]):
...     print "It's bigger"
... 
It's bigger

OTHER TIPS

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))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top