Python Tutorial
Python Loop Tuples
Loop through tuple items with for or while.
for and while
Iterate items or indexes.
thistuple = ("apple", "banana", "cherry")
for x in thistuple:
print(x)
for i in range(len(thistuple)):
print(thistuple[i])📘 Real-World Deep Dive
Tuple iteration is identical to list iteration — <code>for x in t</code>, <code>enumerate</code>, parallel with <code>zip</code>, comprehension, star-unpack. The wins come from pickling it where the data shouldn't change.
Real-Life Scenario
A small daily-error digest built from a tuple of <code>(day, count)</code> pairs. Notice tuples make the digest stable across the build.
Real-Life Example
from datetime import date
events: tuple[tuple[date, str, int], ...] = (
(date(2026, 8, 18), "timeout", 3),
(date(2026, 8, 18), "refusal", 1),
(date(2026, 8, 19), "refusal", 4),
(date(2026, 8, 19), "timeout", 2),
(date(2026, 8, 20), "refusal", 2),
)
# sort by day, then by count desc
ranked = sorted(events, key=lambda e: (e[0], -e[2]))
# Aggregate per day per kind
by_day_kind: dict[tuple[date, str], int] = {}
for day, kind, n in events: # field unpacking
by_day_kind[(day, kind)] = by_day_kind.get((day, kind), 0) + n
for (day, kind), n in sorted(by_day_kind.items()):
print(f"{day} {kind:<8} {n:>3}")Expected Output
2026-08-18 timeout 3
2026-08-18 refusal 1
2026-08-19 refusal 4
2026-08-19 timeout 2
2026-08-20 refusal 2Common mistakes
- Tuple unpacking with the wrong number of elements raises
ValueError. - Tuples are immutable — a comprehension that filters them produces a fresh tuple, not a generator.
- Logical ordering can hide — star-unpack a tuple of length 3 if you only want 2 elements.
🚀 Performance & Best Practices
- Tuples iterate identically to lists in micro-benchmarks.
- Tuple hashing depends on element contents; immutable lets you safely use
tupleas a dict key. - Compact tuples are interned; don't iterate over a giant tuple repeatedly.
🧪 Try It Yourself
- Sort the digest by total-per-day then by kind alphabetically.
- Build a small
frozendataclass version of the event record. - Profile a comprehension that yields tuples vs. a generator that yields them.