How can I check if a list is sorted in descending order in Python?
Alex K
alex k profile pic

To check if a list is sorted in descending order in Python, you can iterate over the list and compare each element with the next one. If all elements are in descending order, the list is considered sorted in descending order. Here's an example of how you can perform this check:

1
2
3
4
5
6
7
8
9
10
11
12
13
14

def is_sorted_descending(lst):
    for i in range(len(lst) - 1):
   if lst[i] < lst[i + 1]:
  return False
    return True

# Usage:
my_list = [9, 7, 5, 3, 1]

if is_sorted_descending(my_list):
    print("The list is sorted in descending order.")
else:
    print("The list is not sorted in descending order.")

In the above code, theis_sorted_descending() function takes alst parameter representing the list to check. It iterates over the elements of the list using afor loop and compares each element with the next one. If any element is smaller than the next one, it indicates that the list is not sorted in descending order, and the function returnsFalse. If the loop completes without finding any such pair of elements, the function returnsTrue, indicating that the list is sorted in descending order. You can use theis_sorted_descending() function by providing a list as an argument. It will check if the list is sorted in descending order by comparing each element with the next one. The result is then printed accordingly. It's important to note that this approach checks for strict descending order. If you want to allow duplicate values, you can modify the comparison condition toif lst[i] <= lst[i + 1]. Additionally, if you want to check if a list is sorted in descending order without modifying the original list, you can create a copy of the list usinglst.copy() before performing the check. Consider the requirements of your program to determine if this approach suits your needs or if you need to consider other factors such as custom sorting criteria or the presence of duplicate values.