When dealing with a list of values in either ascending (ASC) or descending (DESC) order, it's often necessary to verify the correct ordering of elements. Python, renowned for its user-friendly syntax, offers an elegant way to perform this check.
To ascertain whether a list is sorted in ASC or DESC, consider the following Pythonic solution:
<code class="python">all(l[i] <= l[i+1] for i in range(len(l) - 1))
In this code, "l" represents the input list. The "all" function checks if every element in the generator expression "l[i] <= l[i 1] for i in range(len(l) - 1)" evaluates to True.
For each index "i" in the range up to the length of the list minus one, the expression compares two adjacent elements in "l". If all such comparisons hold true, the list is considered sorted in ASC.
For DESC order verification, simply replace the "<=" operator with ">=" in the expression.
That said, the provided code snippet effectively performs the desired list order verification with a compact and readable syntax.
The above is the detailed content of How to Check if a List is Sorted in Ascending or Descending Order in Python?. For more information, please follow other related articles on the PHP Chinese website!