Python Determine if List is in Ascending Order
We can determine whether a list is in ascending order by writing a function. This function iterates through the elements in the list, checking whether each element is less than or equal to the next element. If all elements satisfy this condition, then the list is in ascending order.
Example
def is_ascending(lst):
for i in range(len(lst) - 1):
if lst[i] > lst[i + 1]:
return False
return True
# Test cases
print(is_ascending([1, 2, 3, 4, 5])) # True
print(is_ascending([1, 3, 2, 4, 5])) # False
print(is_ascending([5, 4, 3, 2, 1])) # False
for i in range(len(lst) - 1):
if lst[i] > lst[i + 1]:
return False
return True
# Test cases
print(is_ascending([1, 2, 3, 4, 5])) # True
print(is_ascending([1, 3, 2, 4, 5])) # False
print(is_ascending([5, 4, 3, 2, 1])) # False
Code analysis:
is_ascendingThe function takes a listlstas a parameter.- Use a
forloop to iterate through the elements in the list, from the first element to the second-to-last element. - In the loop, check whether the current element
lst[i]is greater than the next elementlst[i + 1]. If so, returnFalse, indicating that the list is not in ascending order. - If no element that does not satisfy the condition is found after the loop ends, return
True, indicating that the list is in ascending order.
Output result:
True False FalseOther Extensions
Python3 Examples