Open In App

Iterate over a tuple in Python

Last Updated : 11 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Python provides several ways to iterate over tuples. The simplest and the most common way to iterate over a tuple is to use a for loop.

Below is an example on how to iterate over a tuple using a for loop.

Python
t = ('red', 'green', 'blue', 'yellow')

# iterates over each element of the tuple 't'
# and prints it
for color in t:
    print(color)

Output
red
green
blue
yellow

Let’s discuss other different methods to iterate through tuples.

Using range() with len()

Another way to iterate over a tuple is to use the range() along with len(). This method is useful when we need access to the index of each element.

Python
t = ('red', 'green', 'blue', 'yellow')

# Calculate the lenth of a tuple
n = len(t)

# Iterates through the indices from 0 to 3
for i in range(n):
    print(f"Index {i}: {t[i]}")

Output
Index 0: red
Index 1: green
Index 2: blue
Index 3: yellow

Using while Loop

We can also use a while loop to iterate over a tuple. This method is useful when we want more control over the iteration steps.

Python
t = ('red', 'green', 'blue', 'yellow')

# Start from the first index
i = 0

# Loops till the last index (i.e., 3)
while i < len(t):
    print(t[i])
    i += 1

Output
red
green
blue
yellow

Using enumerate()

We can use the enumerate() function of iterate over the tuple, if we need the index along with the value. This function returns both the index and the corresponding value of the tuple.

Python
t = ('red', 'green', 'blue', 'yellow')

# Here, i and color stores the index and value respectively
for i, color in enumerate(t):
    print(f"Index {i}: {color}")

Output
Index 0: red
Index 1: green
Index 2: blue
Index 3: yellow

Related Articles:



Next Article

Similar Reads