Skip to main content

How to check if a list is sorted in Python

How to check if a list is sorted in Python.

Here's a step-by-step tutorial on how to check if a list is sorted in Python.

1: Understand the problem

To check if a list is sorted, we need to ensure that each element in the list appears in ascending order.

2: Determine the approach

There are multiple approaches to check if a list is sorted. We can use built-in functions, loops, or list comprehensions. In this tutorial, we'll cover a few different methods.

Method 1: Using the sorted() function

The sorted() function in Python returns a new sorted list from the given list. We can compare the original list with the sorted list to check if they are the same.

def is_sorted(lst):
return lst == sorted(lst)

Example usage:

numbers = [1, 2, 3, 4, 5]
print(is_sorted(numbers)) # Output: True

numbers = [5, 4, 3, 2, 1]
print(is_sorted(numbers)) # Output: False

Method 2: Using a loop

We can iterate over the list and compare each element with the next element. If any pair of elements is not in ascending order, we can conclude that the list is not sorted.

def is_sorted(lst):
for i in range(len(lst) - 1):
if lst[i] > lst[i + 1]:
return False
return True

Example usage:

numbers = [1, 2, 3, 4, 5]
print(is_sorted(numbers)) # Output: True

numbers = [5, 4, 3, 2, 1]
print(is_sorted(numbers)) # Output: False

Method 3: Using list comprehension

We can use list comprehension to create a new list of booleans indicating if each element is less than or equal to the next element. If all elements in the new list are True, the original list is sorted.

def is_sorted(lst):
return all(lst[i] <= lst[i + 1] for i in range(len(lst) - 1))

Example usage:

numbers = [1, 2, 3, 4, 5]
print(is_sorted(numbers)) # Output: True

numbers = [5, 4, 3, 2, 1]
print(is_sorted(numbers)) # Output: False

3: Test the code

You can test the code using different lists, including empty lists, lists with a single element, and lists with random elements, to ensure that it functions correctly in all scenarios.

That's it! You now have multiple methods to check if a list is sorted in Python. Choose the method that suits your requirement and integrate it into your code.