How to Check if a List is Sorted in Descending Order in Python

This code defines a function that returns True if a given list is sorted in descending order, using a generator expression with all() to compare each adjacent pair.

Easy Python 3.6+ Aug 9, 2026 Lists & loops 13 views 0 copies

Python code

16 lines
Python 3.6+
def is_descending(lst):
    """Return True if list is sorted in descending order."""
    return all(lst[i] >= lst[i + 1] for i in range(len(lst) - 1))


if __name__ == "__main__":
    test_cases = [
        [5, 4, 3, 2, 1],
        [3, 3, 2, 1],
        [1, 2, 3],
        [10, 8, 9],
        []
    ]

    for case in test_cases:
        print(f"{case} -> {is_descending(case)}")

Output

stdout
[5, 4, 3, 2, 1] -> True
[3, 3, 2, 1] -> True
[1, 2, 3] -> False
[10, 8, 9] -> False
[] -> True

How it works

The function uses all() to check that every consecutive pair satisfies lst[i] >= lst[i + 1]. For an empty list, range(len(lst) - 1) produces an empty range, so all() returns True vacuously. The generator expression avoids creating an intermediate list of booleans, making it memory efficient. Duplicates are allowed because equal elements still satisfy the condition.

Common mistakes

  • Using `>` instead of `>=`, which would incorrectly reject lists with equal adjacent elements.
  • Forgetting the empty list edge case, where the function should return True.
  • Creating a full list of booleans with a list comprehension, wasting memory on large lists.

Variations

  1. Use `all(a >= b for a, b in zip(lst, lst[1:]))` for a more Pythonic syntax.
  2. Check ascending order by changing the comparison to `<=`.

Real-world use cases

  • Validating that user input or API data is already sorted before running an algorithm that expects sorted input.
  • Checking if a score list is ranked from highest to lowest for leaderboard display.
  • Detecting if a data series is monotonically decreasing for trend analysis in time-series data.

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.