tuple.count()
Python · Tuples
Theory
.count(value) returns how many items in a tuple are equal (==) to value. With colors = ('red', 'green', 'red'), colors.count('red') is 2. If the value never appears the result is 0, never an error. The comparison is exact equality, so string matching is case-sensitive: 'Red' does not match 'red'.
Tuples have only two methods, count() and index(), because every other list method (append, remove, sort...) would change the sequence, and tuples are immutable. count() does not modify anything; it scans every item once, which is O(n). For counting all distinct values in one pass, collections.Counter(colors) is better than calling count() for each value. Everything else you do with tuples, like len(), in, slicing and sorted(), uses general built-in functions and operators rather than methods.
Why we use it
Tuples often hold fixed sets of responses, survey choices or log records. count() gives a quick frequency for one value without converting the tuple to a list or writing a loop.
When to use it
Use count() for a quick tally of one value in a tuple. Use collections.Counter to count every value, and in when you only need to know whether a value is present at all.
How it works
- Call colors.count('red')
- Set a counter to 0
- Visit each item of the tuple in order
- Is the item == 'red'? Yes: Add 1 to the counter. No: Leave it.
- Return 2 after the last item; the tuple is unchanged
Syntax
tuple.count(value)Example
colors = ('red', 'green', 'red')
print(colors.count('red'))Key points
- One of only two methods tuples support, since they're immutable
- Returns 0 rather than an error if the value is absent
- Uses == comparison, so 'Red' does not match 'red'
- Scans every item (O(n)); does not change the tuple
- Use collections.Counter to count all values at once