Stop Sorting Just to Check Order: 5 Fast O(n) Methods in Python
Source: Dev.to
The Problem With Using sort() Just to Verify Order
A common mistake (and one I’ve made myself):
def is_sorted_bad(lst):
return lst == sorted(lst)Python’s Timsort is O(n log n) and copies the whole list.
For a million elements that’s roughly 20 million operations and extra memory—just for a yes/no answer! 😩
Order Types
- Non‑decreasing (allows duplicates)
lst[i + 1]:
return False
return Trueall() + range
def is_sorted(lst):
return all(lst[i] = y for x, y in zip(lst, lst[1:]))Edge Cases
- Empty or single‑element lists → Always
True - Mixed types →
TypeError(wrap intry/except) Nonevalues → Handle manually
Comparison of Methods
| Method | Time / Space Notes | Best For |
|---|---|---|
all() + zip() | Readable, common | Everyday use |
for loop | Clear, no tricks | Interviews |
all() + range() | Useful when index is needed | Extensions (e.g., finding first violation) |
pairwise() | True O(1) space | Modern Python (3.10+) |
operator.le (or operator) | Great for custom objects | Key‑based or attribute sorting |
NumPy & Pandas Shortcuts
# NumPy
np.all(arr[:-1] <= arr[1:])# Pandas
series.is_monotonic_increasingWhen You Need the Sorted List Anyway
If you already need the sorted list, just call .sort()—Timsort runs in O(n) on already‑sorted data!
Which method do you use most? Drop a comment below 👇