Guide Python Beginner

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.

2 min read

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() and index() — 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 called append to 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), or t.sort() on a tuple — none exist; Python raises AttributeError: 'tuple' object has no attribute 'append' (and so on) rather than silently doing nothing.
  • Using index() when the value might not be present — it raises ValueError, same as list.index(); check in first or catch the exception.
  • Expecting count() or index() to accept a start/stop range the way str.find() does — tuple.index() does actually accept optional start/stop arguments, but it’s easy to forget since count() does not.

Add More Questions to This Guide

Know a question that should be here? Share it and help the community!

Open Google Form