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.

Easy Python 3.9+ Aug 9, 2026 Lists & loops 19 views 0 copies

Python code

14 lines
Python 3.9+
def 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

stdout
[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

  1. Use `list == sorted(lst)` but this is O(n log n) and creates a copy.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Lists & loops

Related tutorials and quizzes for this topic.