Tuples in Python are ordered, immutable collections. Even though you cannot change their items, you can easily loop through them to read or process data. You can use:
for loops for simple iteration.range() and len().while loops when you need more control over the index.enumerate() to get both index and value together.for loop.while loops require you to manually control the index variable.enumerate() is a Pythonic way to get index and value in one step.Loop directly over each item in the tuple.
for item in my_tuple:Use range() and len() to access items by index.
for i in range(len(my_tuple)):Manually control the index variable.
while i < len(my_tuple):Get both index and value at the same time.
for index, value in enumerate(my_tuple):The simplest way to iterate over a tuple is using a for loop. Each item is accessed one by one.
fruits = ("apple", "banana", "cherry")
# Loop through each fruit in the tuple
for fruit in fruits:
print(fruit)
apple banana cherry
Use range() and len() when you need the index along with the item.
fruits = ("apple", "banana", "cherry")
# Use the index to access each fruit
for i in range(len(fruits)):
print(f"Index {i}: {fruits[i]}")
Index 0: apple Index 1: banana Index 2: cherry
A while loop gives you more control over how and when the index changes.
fruits = ("apple", "banana", "cherry")
i = 0
# Iterate using a while loop and manual index
while i < len(fruits):
print(f"Item {i}: {fruits[i]}")
i += 1
Item 0: apple Item 1: banana Item 2: cherry
enumerate() provides a clean way to get both index and value in each iteration.
fruits = ("apple", "banana", "cherry")
# Use enumerate to get both index and value
for index, fruit in enumerate(fruits):
print(f"Index {index} -> {fruit}")
Index 0 -> apple Index 1 -> banana Index 2 -> cherry
For tuples that contain other tuples (nested tuples), use nested for loops.
matrix = ((1, 2), (3, 4), (5, 6))
# Outer loop goes through each inner tuple (row)
for row in matrix:
# Inner loop goes through each value in the row
for item in row:
print(item, end=" ")
print()
1 2 3 4 5 6
In all the examples above, the loop visits each item in the tuple in order. For basic for loops, the loop variable (fruit, row, item) directly holds each element.
i or index tracks position, and you use it to access items like fruits[i].for item in tuple loop for readability.enumerate() when you need both index and value.while, always update the index (e.g., i += 1) to avoid infinite loops.for loop to print only the odd numbers.enumerate() on a tuple of strings to display each item with its index.((1, 2), (3, 4), (5, 6))) and print each inner element separately.while loop that iterates through a tuple and stops when a specific value is found.