0
0
PythonHow-ToBeginner · 3 min read

How to Iterate Over Tuple in Python: Simple Guide

To iterate over a tuple in Python, use a for loop to access each element one by one. You can write for item in tuple: followed by the code to process each item.
📐

Syntax

Use a for loop to go through each element in the tuple. The syntax is simple:

  • for element in tuple: — starts the loop over each item.
  • element — variable holding the current item.
  • Indented block — code to run for each item.
python
for element in tuple:
    # do something with element
💻

Example

This example shows how to print each item in a tuple of fruits.

python
fruits = ('apple', 'banana', 'cherry')
for fruit in fruits:
    print(fruit)
Output
apple banana cherry
⚠️

Common Pitfalls

One common mistake is trying to change tuple items inside the loop, but tuples are immutable (cannot be changed). Also, avoid using index-based loops unless necessary, as direct iteration is simpler and cleaner.

python
numbers = (1, 2, 3)

# Wrong: trying to change tuple items (will cause error)
# for i in range(len(numbers)):
#     numbers[i] = numbers[i] * 2  # TypeError

# Right: create a new list instead
doubled = [num * 2 for num in numbers]
print(doubled)
Output
[2, 4, 6]
📊

Quick Reference

Tips for iterating over tuples:

  • Use for item in tuple: for simple and readable code.
  • Tuples cannot be changed; create new collections if you need to modify data.
  • Use list comprehensions if you want to transform tuple items into a list.

Key Takeaways

Use a for loop to iterate over each element in a tuple.
Tuples are immutable; you cannot change their items during iteration.
Direct iteration is simpler than using indexes for tuples.
Use list comprehensions to create new lists from tuple items.
Always write clear and readable loops for better code.