pythonalgorithmlistsorting

Pythonic way to check if a list is sorted or not


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.


Solution

  • Here is a one liner:

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

    If using Python 2, use xrange instead of range.

    For reverse=True, use >= instead of <=.