Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python – Check for descending Sorted list
A list is a data structure in Python that stores elements within square brackets. Lists can be sorted in ascending order (each element is smaller than the next) or descending order (each element is larger than the next). This article demonstrates three methods to check if a list is sorted in descending order.
Using Iteration Method
This approach iterates through the list and compares each element with the next one. If any element is smaller than the next element, the list is not in descending order ?
def is_descending(numbers):
# Iterate through the list starting from the second element
for i in range(1, len(numbers)):
# If current element is greater than previous, not descending
if numbers[i] > numbers[i-1]:
return False
return True
# Test with a list not in descending order
num_list = [45, 32, 12, 98, 100]
if is_descending(num_list):
print("Given list follows descending order.")
else:
print("Descending order is not followed.")
Descending order is not followed.
Using sorted() Function
This method compares the original list with its sorted version in reverse order. If they match, the list is already in descending order ?
def is_descending(numbers):
# Compare list with its sorted reverse version
return numbers == sorted(numbers, reverse=True)
# Test with a list in descending order
num_list = [98, 45, 32, 12]
if is_descending(num_list):
print("Given list follows descending order.")
else:
print("Descending order is not followed.")
Given list follows descending order.
Using reduce() Function
The reduce() function from the functools module applies a function cumulatively to check if consecutive elements maintain descending order ?
from functools import reduce
def is_descending(numbers):
# Use reduce to check if each pair maintains descending order
return all(numbers[i] >= numbers[i+1] for i in range(len(numbers)-1))
# Test with a list in descending order
num_list = [98, 45, 32, 12]
if is_descending(num_list):
print("Given list follows descending order.")
else:
print("Descending order is not followed.")
Given list follows descending order.
Comparison
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Iteration | O(n) | O(1) | Memory efficient, early termination |
| sorted() | O(n log n) | O(n) | Simple one-liner solution |
| reduce() | O(n) | O(1) | Functional programming approach |
Conclusion
The iteration method is most efficient for checking descending order as it stops early when finding an out-of-order element. Use sorted() for simple readable code, and reduce() for functional programming style.
