Use for
loop statement to iterate the tuple items in python.
colors_tuple = ("Red", "Blue", "Green")
for color in colors_tuple:
print(color)
Red
Blue
Green
In the above example, we are iterating the colors_tuple
by using the for
loop statement and printing the items from the tuple.
You can also fetch tuple items by referring its the index number while iterating the loop.
colors_tuple = ("Red", "Blue", "Green")
for i in range(len(colors_tuple)):
print(colors_tuple[i])
Red
Blue
Green
For the iteration of for loop, we used range()
and len()
methods. Here range()
function represents an immutable sequence of numbers, and len()
returns the number of items in the tuple.
This example creates an iterable with values of [0, 1, 2]
.
You can also use the while
loop statement to iterate the tuple items in python.
While iterating the tuple items using the while
loop, use the len()
function to determine the number of items in the tuple, then start loop iteration from 0
using temporary variable declarations and increment that variable by 1
for each iteration.
colors_tuple = ("Red", "Blue", "Green")
i = 0
while i < len(colors_tuple):
print(colors_tuple[i])
i = i + 1
Red
Blue
Green
In the above example, we are iterating the colors_tuple
by using the while
loop statement and printing the items from the tuple.