Python Tuple While Loop

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.

Examples

1. Iterate over given 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.

Python Program

tuple1 = ('a', 'e', 'i', 'o', 'u')

index = 0

while index<len(tuple1):
    #do something
    print(tuple1[index])
    #increment index
    index = index+1
Run Code Copy

Output

a
e
i
o
u

2. Iterate over a Tuple of numbers using 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.

Python Program

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)
Run Code Copy

Output

34

Summary

In this tutorial of Python Examples, we learned how to use while loop to iterate over the items of a Tuple in Python.

Related Tutorials

Code copied to clipboard successfully 👍