How can I check if a list is sorted in ascending or descending order in Python?
Gable E
gable e profile pic

In Python, you can check if a list is sorted in ascending or descending order by comparing each element with its adjacent elements. Here's a detailed explanation of how to perform these checks: Checking for Ascending Order: To check if a list is sorted in ascending order, iterate over the list and compare each element with the next element. If any element is greater than the next element, the list is not sorted in ascending order.

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

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

my_list = [1, 2, 3, 4, 5]

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

In this example, theis_sorted_ascending() function compares each element of the list with its adjacent element using a loop. If any element is greater than the next element, the function returnsFalse, indicating that the list is not sorted in ascending order. If all elements are in ascending order, the function returnsTrue. Checking for Descending Order: To check if a list is sorted in descending order, iterate over the list and compare each element with the next element. If any element is less than the next element, the list is not sorted in descending order.

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

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

my_list = [5, 4, 3, 2, 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 this example, theis_sorted_descending() function compares each element of the list with its adjacent element using a loop. If any element is less than the next element, the function returnsFalse, indicating that the list is not sorted in descending order. If all elements are in descending order, the function returnsTrue. Summary: To check if a list is sorted in ascending or descending order in Python, you can iterate over the list and compare each element with its adjacent element. If all elements satisfy the desired ordering, the list is considered sorted. If any element violates the ordering, the list is not sorted in the specified order. Understanding how to perform these checks allows you to validate the order of elements in a list and make informed decisions based on the sortedness of the data.