Python Tuple – Iterate using While Loop
You can use While Loop with Python Tuple to iterate over the items present in a Python Tuple.
You may need Tuple Length to keep the bounds and indexing to access the items of Tuple.
Example 1: Iterate over Tuple using While Loop
In this example program, we defined a tuple with some string values. Then we used while loop to print each item of the tuple. We shall define an int to hold the index and we shall increment the index during each iteration. And during each iteration, we access the next element of Tuple using index.
tuple1 = ('a', 'e', 'i', 'o', 'u') index = 0 while index<len(tuple1): #do something print(tuple1[index]) #increment index index = index+1
a e i o u
Example 2: Tuple While Loop
In this example Python program, we defined a tuple with some numbers. Then we used while loop to iterate over the Tuple items and sum them.
tuple1 = (5, 3, 2, 8, 4, 4, 6, 2) sum = 0 index = 0 while index<len(tuple1): sum = sum + tuple1[index] #increment index index = index+1 print(sum)
In this tutorial of Python Examples, we learned how to use while loop to iterate over the items of a Tuple in Python.