11.6 Tuple Methods
Why a tuple has exactly two methods, count() and index(), and how that short list is a direct, mechanical consequence of immutability -- every method that would modify a list simply has nothing to exist for.
Tuples have only two methods — a direct consequence of immutability. Every method that would modify a list (append, remove, sort, …; see 10.7 List Methods) simply doesn’t exist for tuples, since there’s nothing for it to do.
count()
Counts how many times a value appears.
>>> t = (1, 2, 3, 2, 1)
>>> t.count(2)
2
index()
Returns the position of the first matching value; raises ValueError if absent — the same contract as list.index().
>>> t.index(2)
1
Quick Interview Answer
“A tuple has exactly two methods,
count()andindex()— both read-only. Every list method that mutates (append,insert,remove,sort,reverse, …) has no tuple equivalent at all, not because it was left out, but because immutability makes it structurally meaningless — there’s no operation for a method calledappendto perform on an object that can never grow. This short method list is itself one of the clearest signals of what immutability actually costs and buys: fewer things you can do, in exchange for the guarantees covered in 11.9 Immutability and Copying.”
Common Mistakes
- Calling
t.append(x),t.remove(x), ort.sort()on a tuple — none exist; Python raisesAttributeError: 'tuple' object has no attribute 'append'(and so on) rather than silently doing nothing. - Using
index()when the value might not be present — it raisesValueError, same aslist.index(); checkinfirst or catch the exception. - Expecting
count()orindex()to accept astart/stoprange the waystr.find()does —tuple.index()does actually accept optionalstart/stoparguments, but it’s easy to forget sincecount()does not.
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form