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.
Python code
16 linesdef 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
[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
- Use `all(a >= b for a, b in zip(lst, lst[1:]))` for a more Pythonic syntax.
- 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
More from Lists & loops
- Check if List is Sorted Ascending in Python easy
- 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
Keep learning
Related tutorials and quizzes for this topic.