Stop Sorting Just to Check Order: 5 Fast O(n) Methods in Python

Published: (February 17, 2026 at 12:41 AM EST)
2 min read
Source: Dev.to

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 True

all() + 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 in try/except)
  • None values → Handle manually

Comparison of Methods

MethodTime / Space NotesBest For
all() + zip()Readable, commonEveryday use
for loopClear, no tricksInterviews
all() + range()Useful when index is neededExtensions (e.g., finding first violation)
pairwise()True O(1) spaceModern Python (3.10+)
operator.le (or operator)Great for custom objectsKey‑based or attribute sorting

NumPy & Pandas Shortcuts

# NumPy
np.all(arr[:-1] <= arr[1:])
# Pandas
series.is_monotonic_increasing

When 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 👇

Original article source

0 views
Back to Blog

Related posts

Read more »