Python – Loop Tuples
Why Loop Through Tuples?
Tuples are ordered collections, so you can loop through them just like lists to access, display, or process each element.
Python provides multiple ways to loop through tuples using:
for
loopfor
loop withrange()
while
loopenumerate()
1. Using a Simple for
Loop
Example:
colors = ("red", "green", "blue")
for color in colors:
print(color)
Output:
red
green
blue
2. Using for
Loop with range()
and Indexing
This method is helpful when you also need the index of each item.
Example:
colors = ("red", "green", "blue")
for i in range(len(colors)):
print(f"Index {i}: {colors[i]}")
Output:
Index 0: red
Index 1: green
Index 2: blue
3. Using while
Loop
You can use a while
loop with a counter to access each item by index.
Example:
colors = ("red", "green", "blue")
i = 0
while i < len(colors):
print(colors[i])
i += 1
Output:
red
green
blue
4. Using enumerate()
to Get Index and Value
enumerate()
lets you loop over a tuple and get both the index and the value at the same time.
Example:
colors = ("red", "green", "blue")
for index, value in enumerate(colors):
print(f"{index}: {value}")
Output:
0: red
1: green
2: blue
5. Looping Over Nested Tuples
When your tuple contains sub-tuples, you can use tuple unpacking while looping.
Example:
students = (("Alice", 85), ("Bob", 90), ("Charlie", 78))
for name, marks in students:
print(f"{name} scored {marks}")
Output:
Alice scored 85
Bob scored 90
Charlie scored 78
Summary
Loop Type | Use Case |
---|---|
for loop | Simple iteration |
for with range() | When index is needed |
while loop | Full control with condition |
enumerate() | Access index and value together |
Nested tuple loop | Access elements inside sub-tuples |