Loop Tuples
Python – Loop Tuples
Looping through tuples in Python allows you to read and process each element efficiently.
Since tuples are ordered and immutable, looping is the primary way to work with their data.
This topic covers all common and practical ways to loop through tuples.
Loop Through a Tuple Using for
The most common and readable approach.
python
fruits = ("apple", "banana", "cherry")
for fruit in fruits:
print(fruit)
python
numbers = (1, 2, 3, 4)
for num in numbers:
print(num)
Loop Using Index Numbers
Use this method when you need the index position.
python
colors = ("red", "green", "blue")
for i in range(len(colors)):
print(colors[i])
python
for i in range(len(colors)):
print(i, colors[i])
Loop Using while
The
while loop provides manual control.python
numbers = (10, 20, 30)
i = 0
while i < len(numbers):
print(numbers[i])
i += 1
Loop Using enumerate()
enumerate() gives index and value together.python
fruits = ("apple", "banana", "cherry")
for index, value in enumerate(fruits):
print(index, value)
python
for index, value in enumerate(fruits, start=1):
print(index, value)
Loop Using Tuple Unpacking
python
pairs = ((1, 2), (3, 4), (5, 6))
for a, b in pairs:
print(a, b)
Loop Through Nested Tuples
python
matrix = (
(1, 2),
(3, 4),
(5, 6)
)
for row in matrix:
for value in row:
print(value)
Loop with Conditions
python
numbers = (10, 15, 20, 25)
for n in numbers:
if n > 15:
print(n)
Loop with break
Stops loop execution.
python
numbers = (1, 2, 3, 4, 5)
for n in numbers:
if n == 3:
break
print(n)
Loop with continue
Skips current iteration.
python
numbers = (1, 2, 3, 4, 5)
for n in numbers:
if n == 3:
continue
print(n)
Loop with zip() (Advanced)
Loop through multiple tuples together.
python
names = ("A", "B", "C")
scores = (80, 90, 85)
for name, score in zip(names, scores):
print(name, score)
Loop Through Tuple in Reverse
python
numbers = (1, 2, 3)
for n in reversed(numbers):
print(n)
Common Mistakes
Trying to Modify Tuple Inside Loop
python
t = (1, 2, 3)
# t[0] = 10 # TypeError
Tuples cannot be modified.
Performance Note
- Tuples are faster to iterate than lists
- Ideal for read-only data
- Safer for constant data structures
Summary
- Use
forloop for simplicity - Use index when position matters
enumerate()improves readability- Tuple unpacking simplifies nested loops
- Tuples are read-only during iteration
- Excellent for fixed and constant data