If you've ever needed to validate if a tuple in Python is sorted—maybe for data integrity or interview prep—this guide has you covered. Tuples are immutable, so no in-place sorting like lists. Instead, we'll focus on efficient pairwise checks that run in O(n) time with early exits.
We'll cover 5 methods, from one-liners to loop-based approaches, plus tips for descending order, keys, and edge cases.
Why Check Tuples Differently?
Tuples can't be sorted in place (t.sort() raises AttributeError). sorted(t) returns a list, which is wasteful for just a boolean. Our methods avoid sorting entirely.
Method 1: all() with zip() (Recommended)
def is_sorted(t):
return all(x <= y for x, y in zip(t, t[1:]))
- Non-decreasing (duplicates OK).
- For strict: Use <.
- Handles empty/single-element: True.
How it works: Pairs elements (e.g., (1,2), (2,3)) and checks lazily.
Method 2: For Loop (Interview Favorite)
def is_sorted(t):
for i in range(len(t) - 1):
if t[i] > t[i + 1]:
return False
return True
Clear and extensible (e.g., return violation index).
Method 3: all() with range()
def is_sorted(t):
return all(t[i] <= t[i + 1] for i in range(len(t) - 1))
Index-based one-liner.
Method 4: itertools.pairwise() (Python 3.10+)
from itertools import pairwise
def is_sorted(t):
return all(x <= y for x, y in pairwise(t))
Memory-efficient—no slicing.
Method 5: sorted() Comparison (Simple but Slow)
def is_sorted(t):
return t == tuple(sorted(t))
O(n log n)—use for small tuples only.
Descending and Key-Based Checks
For descending: Flip to >= or >.
For keys (e.g., sort by salary in records):
import operator
def is_sorted_by(t, key=operator.itemgetter(2)):
return all(key(x) <= key(y) for x, y in zip(t, t[1:]))
Edge Cases Quick Hits
- Empty/single: True.
- Duplicates: OK with <=.
- Mixed types: Wrap in try-except.
- Nested tuples: Lexicographic by default.
- None: Custom compare function.
Performance
All but Method 5 are O(n) with early exit. See the full article for a timeit benchmark script!
These work on lists too—tuples/lists are sequences at heart.
What’s your go-to method? Share in the comments! For more details, including FAQs and resources, head to the original post on EmiTechLogic.
Related Articles
Want to dive deeper into Python sequences, performance, or related concepts? Here are some hand-picked reads from EmiTechLogic:
- Python Tuples – Everything You Need to Know — Deep dive into tuples (immutability, methods, use cases).
- Check if List is Sorted in Python — Similar techniques adapted for mutable lists.
- Python Optimization Guide: How to Write Faster, Smarter Code — More on avoiding unnecessary sorts and O(n) patterns.
- Python Lists — Complements the tuple discussion with mutable sequences.
- Mutable vs Immutable in Python — Explains why tuples behave differently from lists.
- Python Slicing and Indexing – The Complete Beginner's Guide — Key to understanding t[1:] in Method 1 .
Top comments (0)