Given a list, we may need to check for the sequence of its elements. In this article we will find out if the elements present in the list are in a strictly increasing order. Below programs achieve that objective.
With all and zip
In this approach we first slice each element compare its value to the next element that is sliced. If all such comparisons hold true then we conclude the list is strictly in increasing order.
Example
listA = [11,23,42,51,67] #Given list print("Given list : ",listA) # Apply all and range if (all(i < j for i, j in zip(listA, listA[1:]))): print("Yes, List is sorted.") else: print("No, List is not sorted.") # Checking again listB = [11,23,21,51,67] print("Given list : ",listB) # Apply all and range if (all(i < j for i, j in zip(listB, listB[1:]))): print("Yes, List is sorted.") else: print("No, List is not sorted.")
Output
Running the above code gives us the following result −
Given list : [11, 23, 42, 51, 67] Yes, List is sorted. Given list : [11, 23, 21, 51, 67] No, List is not sorted.
with itertools.starmap
The makes an iterator that computes the function using arguments obtained from the iterable. We zip the list of elements after slicing them one by one and then taking through the less than equal to operator. Please note we have used strings instead of numbers in the below exmaples.
Example
import operator import itertools listA = ['Mon','Tue','Sun'] #Given list print("Given list : ",listA) # Apply all and range if all(itertools.starmap(operator.le, zip(listA, listA[1:]))): print("Yes, List is sorted.") else: print("No, List is not sorted.") # Checking again listB = ['Mon','Sun','Tue'] print("Given list : ",listB) # Apply all and range if all(itertools.starmap(operator.le, zip(listB, listB[1:]))): print("Yes, List is sorted.") else: print("No, List is not sorted.")
Output
Running the above code gives us the following result −
Given list : ['Mon', 'Tue', 'Sun'] No, List is not sorted. Given list : ['Mon', 'Sun', 'Tue'] Yes, List is sorted.