How To Check If List Is Sorted Python

Checking if a list is sorted can be a useful task in programming. In Python, there are several ways to check if a list is sorted, and in this tutorial, we will explore some of them.

Method 1: Using the Sorted() Function

The easiest way to check if a list is sorted is to use the built-in Python function sorted(). This function returns a new sorted list based on the elements of the original list. If the original list is already sorted, the new list will be the same as the original list.

Here is an example code snippet:

The output of this code will be:

List is sorted

Method 2: Using a For Loop

Another way to check if a list is sorted is to use a for loop to check each adjacent pair of elements in the list. If the current element is greater than the next element, then the list is not sorted.

Here is an example code snippet:

The output of this code will be:

List is not sorted

Method 3: Using the All() Function

The all() function returns True if all elements in an iterable are true, and False otherwise. We can use this function along with a for loop to check if all elements in the list are sorted.

Here is an example code snippet:

The output of this code will be:

List is sorted

Conclusion

In this tutorial, we have explored three different methods to check if a list is sorted in Python. Depending on the specific requirements of your program, you can choose the method that works best for you.

Here is the full code that we used in this tutorial: