Python Practice › List Programs › Program 69
Is a list sorted?
Write a Python program to check whether a list is sorted in ascending order.
Input
[1, 2, 3, 5, 7, 8, 9], [3, 5, 1, 6, 8, 2, 4]
Output
True False
Approach
- Every item must be less than or equal to the next one.
Solution
def is_sorted(items): return all(a <= b for a, b in zip(items, items[1:])) print(is_sorted([1, 2, 3, 5, 7, 8, 9]), is_sorted([3, 5, 1, 6, 8, 2, 4]))Output
True False
Line by line
Line 2
Checking neighbours is faster than comparing with sorted(items).
Learn the concept
New to this topic? Read the lesson, then come back.