Python Tutorial
Python Tuple Methods
Tuples have two built-in methods: count() and index().
count() and index()
count how many times a value appears. index returns the first position.
thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)
print(thistuple.count(5))
print(thistuple.index(8))📘 Real-World Deep Dive
A tuple has exactly two methods — <code>count()</code> and <code>index()</code> — and that tiny surface area is the point. When you want a value that <em>can't</em> be edited by accident, the short method list is a feature, not a limitation.
Real-Life Scenario
A game records each roll of a die as a fixed, tamper-proof history. We tally the results with count() and find when a value first appeared with index().
Real-Life Example
rolls = (4, 2, 6, 4, 1, 4, 3, 6)
# count(): how many times did each face come up?
for face in range(1, 7):
print(f"face {face}: {rolls.count(face)}")
# index(): the first turn a six was rolled (0-based)
print("first six on turn", rolls.index(6) + 1)count() and index() read a tuple without changing it — perfect for data you want to keep read-only.
Expected Output
face 1: 1
face 2: 1
face 3: 1
face 4: 3
face 5: 0
face 6: 2
first six on turn 3Common mistakes
index()raisesValueErrorif the item is missing — guard withif x in tfirst, or catch the exception.index()returns only the first match. For every position, use[i for i, v in enumerate(t) if v == x].- Tuples have no
append/sort/remove— if you find yourself wanting those, you wanted a list all along.
🚀 Performance & Best Practices
count()andindex()both scan the tuple (O(n)). Counting every distinct value at once is faster withcollections.Counter— one pass instead of one pass per value.- Tuples are slightly smaller and faster to build than equivalent lists, which is why Python uses them for function returns and dict keys.
- Because they're immutable and hashable, tuples can be set members and dict keys — lists can't.
🧪 Try It Yourself
- Replace the per-face loop with a single
collections.Counter(rolls)and compare the output. - Write
all_positions(t, value)that returns every index ofvalue, not just the first. - Find the most common face in one line using
max(range(1, 7), key=rolls.count)and explain its cost.