Check if a List is sorted in Python

In the previous article, we saw how we can obtain a count of all the distinct elements of a list. Now we will look at how we can implement a program to Check if a List is sorted in Python. We need to check if the list is in non-decreasing order, as in every element of the list should be either greater than the previous element or equivalent in value to the previous element. There is no condition for the first element.

In the list l=[10,20,30], the program should return it as ‘Yes’ which means it matches the conditions for sorting, In the case of l=[10,20,20,39] the program still returns a ‘Yes’. However if the list only contains a single value or even empty, by default it should still return ‘Yes’.

Writing a program to Check if a List is sorted in Python

We need to write a function that can receive a given list as an argument, and it should return a Boolean value depending on whether or not the List is sorted. One method of doing so would be through the use of while loop. The loop traverses through every element of the list, and checks for both the previous and next element(except for the initial starting element). Immediately upon finding that an element is not in order, we can use the break keyword to terminate the loop and return ‘No’ as output.

def isSorted(l):
     i=1
     while i< len(l):
             if l[i] < l[i-1]:
                return False
             i=i+1
     return True

l=[10,20,30,15,40]
if isSorted(l):
   print("Yes")
else:
   print("No")
Output:
No

Another alternative method to check if a list’s elements follow an ordered pattern is through the use of built-in sorted( ) function.

def isSorted(l):
      sl=sorted(l)
      if sl==l:
         return True
      else:
          return False
l=[10,20,5,30]
if isSorted(l):
   print("Yes")
else:
   print("No")
Output:
No

The sorted( ) function does not modify the original list, but creates a modified one which is sorted. Within this program we compare the original list and the modified one to see if they are equivalent to each other. If the program is in order, and is equal to the modified list the program returns ‘Yes’ as output. Otherwise, the program returns ‘No’.

However, although method 2 is a bit shorter in code, method 1 is more effective as the sorted( ) function involves more work and effort rather than linear traversal of the list. So the first method should ideally be given preference in most-cases.

Leave a Comment