Python Determine Whether a List Is in Ascending Order
We can write a function to determine whether a list is in ascending order. The function iterates over the list elements and checks whether each element is less than or equal to the next one. If all elements satisfy this condition, the list is ascending.
Example
def
is_ascending
(
lst
)
:
for
i
in
range
(
len
(
lst
)
1
)
:
if
lst
[
i
]
lst
[
i +
1
]
:
return
False
return
True
Test cases
(
is_ascending
(
[
1
,
2
,
3
,
4
,
5
]
)
)
True
(
is_ascending
(
[
1
,
3
,
2
,
4
,
5
]
)
)
False
(
is_ascending
(
[
5
,
4
,
3
,
2
,
1
]
)
)
False
Code analysis:
is_ascendingThe function takes a listlstas its argument.- Use
forThe loop iterates over the list elements, from the first to the second-to-last. - In the loop, check whether the current element
lst[i]is greater than the next elementlst[i + 1]. If so, returnFalse, indicating the list is not ascending. - If no element violating the condition is found by the end of the loop, return
True, indicating the list is ascending.
Output result:
True
False
False
Python3 Examples