Pythonic way to check if a list is sorted or not

anijhaw picture anijhaw · Sep 20, 2010 · Viewed 110.7k times · Source

Is there a pythonic way to check if a list is already sorted in ASC or DESC

listtimestamps = [1, 2, 3, 5, 6, 7]

something like isttimestamps.isSorted() that returns True or False.

I want to input a list of timestamps for some messages and check if the the transactions appeared in the correct order.

Answer

Wai Yip Tung picture Wai Yip Tung · Sep 20, 2010

Actually we are not giving the answer anijhaw is looking for. Here is the one liner:

all(l[i] <= l[i+1] for i in xrange(len(l)-1))

For Python 3:

all(l[i] <= l[i+1] for i in range(len(l)-1))