Tuple Methods
Core Methods Deep Dive
Tuples have two built-in methods with important behaviors:
- **count()**: Returns number of occurrences of a value
- **index()**: Finds first position of a value
- **Special Methods**: Implement sequence protocol (__getitem__, __len__, etc.)
- **No Mutating Methods**: Unlike lists, tuples lack append(), remove(), etc.
t = (1, 2, 2, 3, 4, 2, 5)
# count() method
print(t.count(2)) # 3
print(t.count(9)) # 0
# index() method
print(t.index(3)) # 3
print(t.index(2, 2)) # 2 (start searching at index 2)
print(t.index(2, 3, 6)) # 5 (search between indices 3 and 6)
try:
t.index(9)
except ValueError as e:
print(f"Error: {e}")
3 0 3 2 5 Error: tuple.index(x): x not in tuple
Special Method Implementations
Tuples implement several special methods that enable their behavior:
- **Sequence Protocol**: __len__, __getitem__, __contains__
- **Comparison**: __eq__, __lt__, etc. for lexicographical ordering
- **Hashing**: __hash__ for use as dictionary keys
- **Iteration**: __iter__ for for-loops and comprehensions
# Demonstrate special methods
t = (1, 2, 3)
# __len__
print(len(t)) # 3
# __getitem__
print(t[1]) # 2
print(t[1:3]) # (2, 3)
# __contains__
print(2 in t) # True
# __hash__
d = {t: "value"} # Works because tuples are hashable
print(d[t])
# __iter__
for item in t:
print(item)
3 2 (2, 3) True value 1 2 3
Performance Characteristics
Tuple method performance considerations:
- **count()**: O(n) time - must scan entire tuple
- **index()**: O(n) time in worst case
- **in Operator**: O(n) average case (uses __contains__)
- **Hashing**: O(n) for first hash, then O(1) (hash is cached)
from timeit import timeit
setup = "t = tuple(range(1000000))"
print("count(999999):", timeit("t.count(999999)", setup=setup, number=10))
print("index(999999):", timeit("t.index(999999)", setup=setup, number=10))
print("999999 in t:", timeit("999999 in t", setup=setup, number=10))
print("hash(t):", timeit("hash(t)", setup=setup, number=1))
Real-world Method Patterns
Use Case | Method Pattern | Example |
---|---|---|
Data Validation | count() | if t.count(None) > threshold |
Position Finding | index() | idx = headers.index('Date') |
Configuration | in operator | if 'debug' in settings |
Memoization | hash() | @lru_cache(maxsize=None) |
Sequence Protocol | __getitem__ | for x in sequence |