Check if a List is Sorted In Python

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

If you have any query feel free to chat us!

Happy Coding! Happy Learning!

Lecture 85:-  Check if a List is Sorted In Python

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 the all() 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 returns True, indicating that the list is sorted. Otherwise, it returns False.

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 the sorted() function with a custom comparison function to check for sorting.

9. List

Comments: 0

Frequently Asked Questions (FAQs)

How do I register on Sciaku.com?
How can I enroll in a course on Sciaku.com?
Are there free courses available on Sciaku.com?
How do I purchase a paid course on Sciaku.com?
What payment methods are accepted on Sciaku.com?
How will I access the course content after purchasing a course?
How long do I have access to a purchased course on Sciaku.com?
How do I contact the admin for assistance or support?
Can I get a refund for a course I've purchased?
How does the admin grant access to a course after payment?