Understanding the Basics of Sorted and Unsorted Lists

The check for sorted list in python is straightforward. It involves comparing two adjacent elements in the given list using a simple comparison operator, and repeating this process throughout all elem …

Updated November 22, 2023

The check for sorted list in python is straightforward. It involves comparing two adjacent elements in the given list using a simple comparison operator, and repeating this process throughout all elements in the list.

Basics

Python has built-in methods for checking whether a list is sorted or not. Here are some examples to demonstrate them:

# Unsorted list
unsorted_list = [10, 23, 45, 6, 89]
print(all(unsorted_list[i] <= unsorted_list[i + 1] for i in range(len(unsorted_list) - 1))) # False

# Sorted list
sorted_list = [10, 23, 45, 60, 89]
print(all(sorted_list[i] <= sorted_list[i + 1] for i in range(len(sorted_list) - 1))) # True

In the first example, all() is used to check if all elements in the list are True or not. If any element is False, it returns False.

The i variable represents an index of a current number from our list and i + 1 represents the next number in the list. The condition checks if each number is less than or equal to the next one (unsorted_list[i] <= unsorted_list[i + 1]). If it’s true for all numbers, it will return True, indicating that the list is not sorted. Otherwise, it returns False.

In the second example, we have a sorted list and using same logic checks if all elements in the list are less than or equal to the next one which returns True indicating that the list is sorted.

So when we say “How to check if a list is sorted in Python”, it’s not about programming but more about logical thinking.

Hey! Do you love Python? Want to learn more about it?
Let's connect on Twitter or LinkedIn. I talk about this stuff all the time!