11.11 Common Algorithms
Searching, counting, and finding the max/min of a tuple use the exact same techniques as a list -- the only real difference is that a tuple can never be sorted in place.
Search and aggregate operations on a tuple use the exact same techniques as on a list (see 10.12 Sorting and Searching and 10.14 Common Algorithms) — the only difference is a tuple can’t be sorted in place.
Searching
def search(tup, target):
for i, v in enumerate(tup):
if v == target:
return i
return -1
>>> search((5, 2, 8, 1, 9), 8)
2
Counting
>>> (5, 2, 8, 1, 9).count(2)
1
Finding Maximum / Minimum
>>> max((5, 2, 8, 1, 9)), min((5, 2, 8, 1, 9))
(9, 1)
Quick Interview Answer
“Every list algorithm — linear search, counting, finding extremes — applies to a tuple unchanged, since none of them require mutation, only iteration and comparison. The one thing that genuinely doesn’t carry over is in-place sorting:
sorted(some_tuple)works fine and returns a list, but there’s notuple.sort(), because sorting in place is a contradiction for something that can’t be modified. If a sorted tuple is actually needed, wrap the result:tuple(sorted(t)).”
Common Mistakes
- Reaching for
t.sort()on a tuple, forgetting it doesn’t exist — usesorted(t)(returns a list) ortuple(sorted(t))if a tuple result is needed. - Writing a custom linear search for a tuple instead of just using
inor.index()when only presence or a single position is needed, not every algorithmic detail of the search. - Assuming binary search needs adapting for tuples — it works identically, since it only relies on indexing and comparison, neither of which differs from a list.
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form