Check if List is Sorted Ascending in Python
Verify that a list is sorted in ascending order using the all() function and a generator expression.
Python code
14 linesdef is_sorted_ascending(lst):
return all(lst[i] <= lst[i + 1] for i in range(len(lst) - 1))
if __name__ == "__main__":
test_lists = [
[1, 2, 3, 4, 5],
[1, 3, 2, 4, 5],
[5, 4, 3, 2, 1],
[1, 1, 2, 2, 3],
[10],
[]
]
for lst in test_lists:
print(f"{lst}: {is_sorted_ascending(lst)}")
Output
[1, 2, 3, 4, 5]: True
[1, 3, 2, 4, 5]: False
[5, 4, 3, 2, 1]: False
[1, 1, 2, 2, 3]: True
[10]: True
[]: True
How it works
The all() function returns True if every element in the iterable is truthy. Here we pass a generator expression that compares each element with its next neighbor using lst[i] <= lst[i + 1]. The iteration stops at len(lst) - 1 to avoid an IndexError. For empty or single-element lists, the generator yields no items, and all() returns True by convention. This approach is concise, readable, and avoids needing to sort a copy.
Common mistakes
- Using `<` instead of `<=` rejects equal adjacent elements, which are still considered sorted.
- Forgetting to stop at `len(lst) - 1` causes an IndexError.
- Assuming empty or single-element lists are not sorted; they are by definition.
Variations
- Use `list == sorted(lst)` but this is O(n log n) and creates a copy.
- Use `zip(lst, lst[1:])` with `all(x <= y for x, y in zip(lst, lst[1:]))`.
Real-world use cases
- Validate that time-series data timestamps are in chronological order before processing.
- Check that a list of serial IDs from a batch export maintains its ordered sequence.
- Guard against unsorted configuration lists when applying ranked rules in a service.
Sponsored
More from Lists & loops
- Compare Two Lists in Python: Common, Only in First, Only in Second easy
- Convert a List of Integers to a Comma-Separated String in Python easy
- Enumerate a Python List with a Custom Start Index easy
- Extract Data by Type from a List in Python: Numbers and Strings easy
- Find All Occurrences of an Item in a Python List easy
- Find Duplicate Elements in a Python List easy
Keep learning
Related tutorials and quizzes for this topic.