If you have any query feel free to chat us!
Happy Coding! Happy Learning!
You can check if a list is sorted in Python by comparing each element with its adjacent element. If all elements are in ascending order (or descending order for a reverse sort), then the list is considered sorted.
Here's a simple function to check if a list is sorted in ascending order:
pythonCopy code
def is_sorted(lst): return all(lst[i] <= lst[i + 1] for i in range(len(lst) - 1)) # Example usage: sorted_list = [1, 3, 5, 7, 9] unsorted_list = [3, 2, 1, 4, 5] print(is_sorted(sorted_list)) # Output: True print(is_sorted(unsorted_list)) # Output: False
In this example, the
is_sorted()
function takes a list as input and uses a list comprehension along with theall()
function to check if each element (lst[i]
) is less than or equal to the next element (lst[i + 1]
). If all elements meet this condition, the function returnsTrue
, indicating that the list is sorted. Otherwise, it returnsFalse
.To check if the list is sorted in descending order, you can modify the condition in the
is_sorted()
function to use the>=
operator instead of<=
.Keep in mind that the
is_sorted()
function assumes that the list elements are comparable, meaning they support the comparison operators (<
,>
,<=
,>=
). If the list contains complex objects or custom classes, you may need to define a custom sorting criteria or use thesorted()
function with a custom comparison function to check for sorting.
Comments: 0