Is there a pythonic way to check if a list is already sorted in
listtimestamps = [1, 2, 3, 5, 6, 7]
isttimestamps.isSorted() that returns
I want to input a list of timestamps for some messages and check if the the transactions appeared in the correct order.
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))
I would just use
if sorted(lst) == lst: # code here
unless it's a very big list in which case you might want to create a custom function.
if you are just going to sort it if it's not sorted, then forget the check and sort it.
and don't think about it too much.
if you want a custom function, you can do something like
def is_sorted(lst, key=lambda x: x): for i, el in enumerate(lst[1:]): if key(el) < key(lst[i]): # i is the index of the previous element return False return True
This will be O(n) if the list is already sorted though (and O(n) in a
for loop at that!) so, unless you expect it to be not sorted (and fairly random) most of the time, I would, again, just sort the list.