Lists are one of the most used data structures in python. In this article, we will discuss different ways to check for sorted list in python.
How to Check For a Sorted List in Python?
A sorted list has all its elements in non-decreasing order. In other words, the element at index i
is always less than or equal to the element at index i+1
if the list is sorted list. For instance, consider the following lists.
myList1=[1,2,3,4,5,6,7]
myList2=[1,2,3,3,4,5,5]
myList3=[1,2,3,4,2,5,6]
Here, myList1
has all the elements in increasing order if we move from left to right. Hence, it is a sorted list. myList2
doesn’t have its elements in an increasing order but all the elements are in non-decreasing order if we move from left to right. Hence, myList2
is also a sorted list. However, the elements in myList3
are neither in increasing order nor in non-decreasing order. Hence, it is not a sorted list.
Check For Sorted List in Python
To check for a sorted list, we just have to traverse through the list and check if all the elements are in a non-decreasing order or not. For this, we will use a variable isSorted
and a for loop. First, we will initialize the variable isSorted
to True
assuming that the list is already sorted. After that, we will traverse through the list and check if all the elements at index “i”
are less than or equal to the element at the index “i+1”
from index 0 to the end. If we find any element at index “i”
that is greater than the element at index “i+1”
, we will assign the value False
to the isSorted
variable denoting that the list is not sorted. Then we will come out of the loop using the break statement as we have already found that the list is not sorted.
If we do not find any element that is greater than the element at its right, the variable isSorted
will remain True
and will denote that the list is sorted. You can observe this in the following example.
def checkSortedList(newList):
isSorted = True
l = len(newList)
for i in range(l - 1):
if newList[i] > newList[i + 1]:
isSorted = False
return isSorted
myList1 = [1, 2, 3, 4, 5, 6, 7]
myList2 = [1, 2, 3, 3, 4, 5, 5]
myList3 = [1, 2, 3, 4, 2, 5, 6]
print("The list {} is sorted: {} ".format(myList1, checkSortedList(myList1)))
print("The list {} is sorted: {} ".format(myList2, checkSortedList(myList2)))
print("The list {} is sorted: {} ".format(myList3, checkSortedList(myList3)))
Output:
The list [1, 2, 3, 4, 5, 6, 7] is sorted: True
The list [1, 2, 3, 3, 4, 5, 5] is sorted: True
The list [1, 2, 3, 4, 2, 5, 6] is sorted: False
Conclusion
In this article, we have discussed how we can check for sorted list. To know more about lists, you can read this article on list comprehension in python. You might also like this article on dictionary comprehension in python.
Recommended Python Training
Course: Python 3 For Beginners
Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.