A list contains multiple objects in a single variable. Let’s say you have a sorted list and want to check if the list is sorted or not. Then this post will demonstrate it. In this tutorial, you will learn how to check if a List is Sorted in Python.
Methods to Check if a List is Sorted in Python or not
Method 1: Using the sorted() function
The sorted()
function returns a new sorted list, so you can compare it with the original list to check if they are the same. If they are the same, it means the list is already sorted.
def is_sorted(lst):
return sorted(lst) == lst
Example usage
my_list = [10, 20, 30, 40, 50]
print(is_sorted(my_list)) # Output: True
another_list = [50, 40, 30, 20, 10]
print(is_sorted(another_list)) # Output: False
Method 2: Comparing adjacent elements
This method involves iterating through the list and comparing each pair of adjacent elements. If at any point an element is greater than the next element, the list is not sorted.
def is_sorted(lst):
n = len(lst)
for i in range(n - 1):
if lst[i] > lst[i + 1]:
return False
return True
Example usage
my_list = [10, 20, 30, 40, 50]
print(is_sorted(my_list)) # Output: True
another_list = [50, 40, 30, 20, 10]
print(is_sorted(another_list)) # Output: False
Method 3: Using the all() function
The all()
function can be used in combination with a list comprehension. The idea is to check if each element in the list is less than or equal to the next element.
def is_sorted(lst):
return all(lst[i] <= lst[i + 1] for i in range(len(lst) - 1))
Example usage:
my_list = [10, 20, 30, 40, 50]
print(is_sorted(my_list)) # Output: True
another_list = [50, 40, 30, 20, 10]
print(is_sorted(another_list)) # Output: False
Method 4: Using the numpy library
If you have the Numpy library installed, you can use its np.all()
function along with the numpy array to check if the array is sorted.
import numpy as np
def is_sorted(lst):
np_array = np.array(lst)
return np.all(np_array[:-1] <= np_array[1:])
Example usage:
my_list = [1, 2, 3, 4, 5]
print(is_sorted(my_list)) # Output: True
another_list = [5, 4, 3, 2, 1]
print(is_sorted(another_list)) # Output: False
Conclusion
There are many uses for sorted lists. You can quickly search the element, insert, remove, etc. The above is the method that will help you to check if a List is Sorted in Python. You can use any of the above methods at per convenience.
Leave a Reply