Python Program to Check if a List Is Sorted
Beginner · Lists
A list is sorted in ascending order when every element is less than or equal to the one after it. This program compares each pair of neighbours and stops at the first pair that is out of order.
Program
check_list_sorted.py
samples = [[3, 8, 12, 12, 20], [5, 9, 7, 11]] # or: samples = [[int(x) for x in input("Enter numbers: ").split()]]
for numbers in samples:
is_sorted = True
for i in range(len(numbers) - 1):
# Each number must be less than or equal to the next one
if numbers[i] > numbers[i + 1]:
is_sorted = False
break
if is_sorted:
print(numbers, "is sorted in ascending order")
else:
print(numbers, f"is not sorted: {numbers[i]} comes before {numbers[i + 1]}")
Output
[3, 8, 12, 12, 20] is sorted in ascending order [5, 9, 7, 11] is not sorted: 9 comes before 7
How it works
- The program checks two sample lists, one sorted and one not.
- The inner loop compares each element with the next, so it runs up to
len(numbers) - 1to avoid going past the end. - As soon as one element is bigger than the next, the list cannot be sorted, so
breakstops the check. - Equal neighbours, like the two 12s, are allowed, because
>is false for them. - After
break,istill points at the bad pair, so the message can say exactly where the order breaks.
Other ways to write it
Using all() and zip()
Using all() and zip()
def is_sorted(items):
# zip pairs each item with the one after it
return all(a <= b for a, b in zip(items, items[1:]))
for items in [[1, 2, 2, 5], [3, 1, 2], ["apple", "banana", "cherry"]]:
print(items, "sorted:", is_sorted(items))
Output
[1, 2, 2, 5] sorted: True [3, 1, 2] sorted: False ['apple', 'banana', 'cherry'] sorted: True
zip(items, items[1:]) gives the neighbouring pairs, and all() is true only if every pair is in order. It works for strings too.
Comparing with sorted()
Comparing with sorted()
numbers = [3, 8, 12, 12, 20]
print("Sorted in ascending order:", numbers == sorted(numbers))
print("Sorted in descending order:", numbers == sorted(numbers, reverse=True))
Output
Sorted in ascending order: True Sorted in descending order: False
This sorts a copy and compares it with the original. It is easy to write, but it does more work than checking the neighbours.
Try it yourself
Change the program so it checks for descending order instead.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises