Check if list is sorted or not in Python

PythonServer Side ProgrammingProgramming

Lists are the most widely used data collectios in python. We may come across situation when we need to know if the given list is already sorted or not. In this article we will see the approaches to achieve this.

With sort

We take a copy of the given list, apply sort function to it and store that copy as a new list. Then we compare it with the original list and check if they are equal or not.

Example

 Live Demo

listA = [11,23,42,51,67]
#Given list
print("Given list : ",listA)
listA_copy = listA[:]
# Apply sort to copy
listA_copy.sort()
if (listA == listA_copy):
   print("Yes, List is sorted.")
else:
   print("No, List is not sorted.")

# Checking again
listB = [11,23,21,51,67]
#Given list
print("Given list : ",listB)
listB_copy = listB[:]
# Apply sort to copy
listB_copy.sort()
if (listB == listB_copy):
   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 all and range

We can use the all function to check if every element of the list is smaller than the element next to it and apply the range function to traverse through all the elements.

Example

 Live Demo

listA = [11,23,42,51,67]
#Given list
print("Given list : ",listA)
# Apply all and range
if (all(listA[i] <= listA[i + 1] for i in range(len(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(listB[i] <= listB[i + 1] for i in range(len(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.
raja
Published on 13-May-2020 14:33:50
Advertisements