Python Program to Check if List is Sorted
all(lst[i] <= lst[i+1] for i in range(len(lst)-1)), which returns True if the list is sorted in ascending order and False otherwise.Examples
How to Think About It
Algorithm
Code
def is_sorted(lst): return all(lst[i] <= lst[i+1] for i in range(len(lst) - 1)) # Example usage print(is_sorted([1, 2, 3, 4, 5])) # True print(is_sorted([5, 3, 4, 1, 2])) # False print(is_sorted([10])) # True
Dry Run
Let's trace the list [1, 2, 3, 4, 5] through the code
Start checking pairs
Compare 1 <= 2: True
Next pair
Compare 2 <= 3: True
Next pair
Compare 3 <= 4: True
Next pair
Compare 4 <= 5: True
All pairs checked
All comparisons are True, so return True
| Pair | Comparison Result |
|---|---|
| 1 <= 2 | True |
| 2 <= 3 | True |
| 3 <= 4 | True |
| 4 <= 5 | True |
Why This Works
Step 1: Compare each pair
The code checks every pair of neighbors in the list using lst[i] <= lst[i+1] to ensure order.
Step 2: Use all() function
The all() function returns True only if every comparison is True, meaning the list is sorted.
Step 3: Return result
If any pair is out of order, all() returns False, so the function returns False indicating the list is not sorted.
Alternative Approaches
def is_sorted(lst): return lst == sorted(lst) print(is_sorted([1, 2, 3])) # True print(is_sorted([3, 2, 1])) # False
def is_sorted(lst): for i in range(len(lst) - 1): if lst[i] > lst[i+1]: return False return True print(is_sorted([1, 2, 3])) # True print(is_sorted([3, 2, 1])) # False
Complexity: O(n) time, O(1) space
Time Complexity
The code checks each pair once, so it runs in linear time relative to the list size.
Space Complexity
The check uses constant extra space, only storing loop variables and no extra lists.
Which Approach is Fastest?
The all() method and loop with early exit are fastest because they stop early if unsorted; sorting the list is slower due to extra work.
| Approach | Time | Space | Best For |
|---|---|---|---|
| all() with generator | O(n) | O(1) | Clean and efficient for most cases |
| sorted() comparison | O(n log n) | O(n) | Simple but slower for large lists |
| Loop with early exit | O(n) best case | O(1) | Fast exit on unsorted lists |
all() with a generator expression for a clean and efficient sorted check.