VMware ESXi and vSphere Cluster Management
Looping Over a Tuple in Python
Learn how to use Python for loops to visit, print, enumerate, and unpack every value in a tuple.
A tuple is an ordered, immutable Python collection. It stores values in a specific order, and its existing elements cannot be changed after the tuple is created. Tuples are commonly written with parentheses and comma-separated items.
names = ("Maria", "Lucy", "Angelina", "Tanya")
Iteration means visiting collection elements one at a time. Tuple immutability prevents changing existing elements, but it does not prevent reading or processing those values in a loop.
Basic for Loop Syntax
A for loop repeats an indented block once for each item in an iterable. An iterable is an object whose values can be traversed, such as a tuple, list, string, or range() object.
for variable in tuple_variable:
# action for the current tuple item
Python assigns each tuple element to the loop variable in sequence. The indented loop body runs for that element. After the final element has been processed, iteration ends.
| Code part | Meaning |
|---|---|
for | Starts a loop that repeats for each item. |
| Loop variable | The variable that receives the current item during each loop pass. |
in | Connects the loop variable to the iterable being traversed. |
| Tuple variable | The tuple whose values will be visited. |
| Indented loop body | The statements that run once for every tuple item. |
Printing Every Tuple Item
Place print() inside the loop to display each value. Each call below prints one name on its own line, and the output follows the tuple's order.
names = ("Maria", "Lucy", "Angelina", "Tanya")
for name in names:
print(name)
Output:
Maria
Lucy
Angelina
Tanya
On the first pass, name is "Maria". On the next passes it becomes "Lucy", "Angelina", and "Tanya". The loop then finishes.
Tuples and Lists Use the Same Loop Structure
The collection type changes the literal syntax and mutability, but the basic for loop syntax is the same for tuples and lists. Parentheses commonly create tuples, while square brackets create lists.
tuple_names = ("Maria", "Lucy")
list_names = ["Maria", "Lucy"]
for name in tuple_names:
print(name)
for name in list_names:
print(name)
| Characteristic | Tuple | List |
|---|---|---|
| Literal syntax | Parentheses, such as ("Maria", "Lucy") | Square brackets, such as ["Maria", "Lucy"] |
Can be iterated with for | Yes | Yes |
| Mutability | Immutable: existing elements cannot be reassigned | Mutable: elements can be changed |
| Output order during iteration | Values are visited in tuple order | Values are visited in list order |
Both collections can be traversed, but a list example is not a tuple example. Choose the delimiters that match the collection you intend to create.
Using enumerate() for Positions
enumerate() is a built-in function that yields both an index and the current item while iterating. Use it when the item's position is also needed.
names = ("Maria", "Lucy", "Angelina", "Tanya")
for position, name in enumerate(names, start=1):
print(position, name)
Output:
1 Maria
2 Lucy
3 Angelina
4 Tanya
Here, position receives the one-based position and name receives the tuple value. Without start=1, enumerate() begins counting at zero.
Unpacking Tuples in a Loop
Unpacking assigns the values in a tuple to multiple variables. If every item in a larger tuple is itself a fixed-size tuple, the loop can unpack each inner tuple directly.
people = (("Maria", 24), ("Lucy", 31))
for name, age in people:
print(f"{name} is {age}")
On each pass, the inner pair is unpacked: its first value goes into name, and its second value goes into age.
Nested Tuples and Nested Loops
A nested tuple contains other tuples. Use nested loops when you need to visit the values at more than one level.
groups = (("Maria", "Lucy"), ("Angelina", "Tanya"))
for group in groups:
for name in group:
print(name)
The outer loop visits each inner tuple. The inner loop then visits each name in that inner tuple. If the structure is consistently made of pairs, direct unpacking may be simpler.
Tuple Iteration Does Not Modify the Tuple
Reading a tuple item in a loop is allowed. Reassigning an item is not, because tuples are immutable.
numbers = (10, 20, 30)
for number in numbers:
print(number)
# This raises TypeError:
# numbers[0] = 99
If changed contents are required, create a new tuple or use a list instead.
numbers = (10, 20, 30)
updated_numbers = (99,) + numbers[1:]
print(updated_numbers)
Common Beginner Errors
Incorrect indentation
Indentation is the leading whitespace that defines which statements belong to a Python code block. Statements that should run for every item must be indented consistently, typically by four spaces.
names = ("Maria", "Lucy")
for name in names:
print(name)
If print(name) is not indented, Python may raise an IndentationError, or the statement may not belong to the loop and therefore may not repeat.
Using the wrong delimiters
Square brackets create a list, not a tuple.
tuple_names = ("Maria", "Lucy")
list_names = ["Maria", "Lucy"]
A one-item tuple requires a trailing comma because parentheses alone can also group an expression:
one_item_tuple = ("Maria",)
not_a_tuple = ("Maria")
Trying to change a tuple item
Iteration lets you inspect or process values; it does not make an immutable tuple editable. An assignment such as names[0] = "New name" raises a TypeError.
Expecting the loop variable to retain every item
The loop variable is overwritten on every iteration. After the loop, it normally retains only the final value.
names = ("Maria", "Lucy", "Angelina")
for name in names:
print(name)
print(name) # Angelina
Process or store values inside the loop when every value must be retained or used later.
Quick Review
- A tuple is an ordered, immutable collection.
- Use
for item in tuple_variable:to visit each item in order. - Put the repeated action in the indented loop body.
- Use
print()inside the loop to display each value. - Tuple and list iteration use the same basic
forsyntax, although their literal syntax and mutability differ. - Use
enumerate()when you need both a position and a value. - Use unpacking when each loop item contains a known number of values.
- A loop variable receives one current value at a time and usually holds the final value after the loop.
For a focused reference, see Looping Over a Tuple.