tuple.count()
Tuples have exactly two methods, count and index, because everything else would mutate. This is the counting half.
Demo
count walks the whole tuple and tallies elements equal to the value. There is no early exit — it always looks at every element, because it cannot know there are no more matches ahead. An absent value gives 0 rather than an error, which is the main difference from index. The demo builds the tuple with tuple([...]) so the call preview stays valid Python.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| value | Any | yes | Value to look for. Compared with ==, so equal-but-not-identical objects still match. |
Return value
int — Number of elements equal to value. Returns 0 rather than raising when there are none.
Common patterns
if t.count(value) > 1: raise ValueError(f"duplicate {value}")
passes = row.count("OK")
from collections import Counter tallies = Counter(t)
Examples
Pitfalls
(1, True, 1.0).count(1)
sum(1 for x in t if x is 1)
tallies = {v: t.count(v) for v in set(t)}
from collections import Counter tallies = Counter(t)
('abc', 'abd').count('ab')
sum(1 for s in t if 'ab' in s)
When to use
- Checking whether a value repeats in a fixed record
- A single tally over a small tuple
- Validating that a value appears exactly once
- Tallying many values → collections.Counter, one pass
- You only need presence → the in operator, which short-circuits
- You want the POSITION → tuple.index
Notes
FAQ
Because tuples are immutable, every method that would append, remove, sort or reverse is impossible. What is left are the two questions you can ask without changing anything: how many (count) and where (index).
[m for m in dir(tuple) if not m.startswith("_")] # ['count', 'index']