Loop Tuples
Comprehensive Iteration Techniques
Tuples support the same iteration techniques as lists. You can loop directly over items, use enumerate() for index-value pairs, reversed() for reverse order, zip() for parallel iteration, and even functional styles like map() or filter().
colors = ('red', 'green', 'blue')
# Basic iteration
print("Basic:")
for color in colors:
print(color.upper())
# With index
print("\nEnumerated:")
for i, color in enumerate(colors, 1):
print(f"{i}. {color}")
# Reversed
print("\nReversed:")
for color in reversed(colors):
print(color)
# Parallel iteration
codes = (1, 2, 3)
print("\nZipped:")
for color, code in zip(colors, codes):
print(f"{color}: {code}")
Basic: RED GREEN BLUE Enumerated: 1. red 2. green 3. blue Reversed: blue green red Zipped: red: 1 green: 2 blue: 3
Advanced Iteration Patterns
Tuples can be unpacked while looping, filtered with conditions, or combined using itertools. These techniques are useful when working with structured or multiple sequences.
from itertools import product, chain
# Nested tuple iteration
matrix = ((1, 2), (3, 4), (5, 6))
print("Nested:")
for row, (x, y) in enumerate(matrix, 1):
print(f"Row {row}: x={x}, y={y}")
# Cartesian product
print("\nProduct:")
for x, y in product((1, 2), ('a', 'b')):
print(x, y)
# Chained iteration
colors = ('red', 'green', 'blue')
print("\nChained:")
for item in chain(colors, ('cyan', 'magenta')):
print(item)
Nested: Row 1: x=1, y=2 Row 2: x=3, y=4 Row 3: x=5, y=6 Product: 1 a 1 b 2 a 2 b Chained: red green blue cyan magenta
Performance Optimization
Tuple iteration is slightly faster than list iteration in some cases because tuples are immutable and avoid resizing overhead. However, in most applications the difference is negligible.
from timeit import timeit
list_time = timeit('for x in lst: pass', 'lst = list(range(1000))')
tuple_time = timeit('for x in tpl: pass', 'tpl = tuple(range(1000))')
print(f"List iteration: {list_time:.3f} μs")
print(f"Tuple iteration: {tuple_time:.3f} μs")
Real-world Applications
Tuple iteration is common when working with structured, immutable data. It is widely used in data processing, game development, finance, and configuration handling.
Domain | Pattern | Example |
---|---|---|
Data Science | Feature iteration | for name, values in dataset.features |
Game Dev | Entity processing | for pos, vel in entities |
Finance | Time series | for date, price in stock_history |
Web Dev | Template rendering | for field, value in form_data |
Systems | Configuration | for key, val in settings.items() |