GICT knowledge base
How to Loop Through Tuples in Python: Working Examples
Published
Use a for loop when you need each value in a Python tuple. Use enumerate() when you also need its position, and unpack the values when each tuple represents a record. The examples below use server names and service ports, but the same patterns work with any tuple.
A tuple is an ordered sequence whose items cannot be replaced, added, or removed in place. Iteration reads its items; it does not make the tuple mutable. See the Python tuple documentation for that distinction.
Loop through the values
This is the simplest option for processing every server name. Save the example in a Python file and run it with python3 filename.py.
servers = ("web-01", "web-02", "backup-01")
for server in servers:
print(server)
Output:
web-01
web-02
backup-01
Each pass assigns the next item to server. If the tuple is empty, the loop body does not run. You do not need a separate length check to handle that case.
Include an item number with enumerate()
For a numbered report, use enumerate() rather than maintaining a counter yourself. The optional start argument changes the displayed counter; it does not change the tuple’s indexing.
servers = ("web-01", "web-02", "backup-01")
for number, server in enumerate(servers, start=1):
print(f"{number}. {server}")
Output:
1. web-01
2. web-02
3. backup-01
If you need the actual zero-based index, omit start=1. Python’s enumerate reference describes the counter and value returned together.
Unpack tuples that represent records
A tuple can contain other tuples. Here, each service record has exactly two fields: a name and a port. Unpacking gives those fields clear names inside the loop.
services = (("ssh", 22), ("https", 443), ("submission", 587))
for name, port in services:
print(f"{name}: {port}")
Output:
ssh: 22
https: 443
submission: 587
Keep the record shape consistent. A three-field record cannot be unpacked into just name, port; Python raises ValueError. When records come from outside your program, validate their shape before processing them.
Stop after finding the item you need
You do not have to process every record. This example stops at the first matching service. The loop’s else branch runs only if no break occurred.
services = (("ssh", 22), ("https", 443), ("submission", 587))
target = "https"
for name, port in services:
if name == target:
print(f"Found {name} on port {port}")
break
else:
print(f"No service named {target}")
Output:
Found https on port 443
Change target to "dns" to exercise the not-found branch. This is a search through the example records, not a network scan or a check that the ports are open.
Iterate in reverse without modifying the tuple
servers = ("web-01", "web-02", "backup-01")
for server in reversed(servers):
print(server)
print(servers)
Output:
backup-01
web-02
web-01
('web-01', 'web-02', 'backup-01')
The final line shows that the original order is unchanged. reversed() supplies an iterator in the opposite direction; see the built-in function reference.
When a while loop is useful
A while loop is an alternative when your algorithm manages an index explicitly. For a simple pass through every item, prefer the shorter for form.
servers = ("web-01", "web-02", "backup-01")
index = 0
while index < len(servers):
print(servers[index])
index += 1
This prints the same three names as the first example. The increment is essential: without it, this loop repeatedly prints the first item. The comparison must be <, not <=, because the last valid index is one less than the length.
Common tuple mistakes
- A single item needs a trailing comma:
("web-01",)is a tuple;("web-01")is a string. Iterating the latter visits characters. - Reassigning the loop variable does not edit the tuple: changing
serverinside the loop only changes that variable. - Tuples do not have list mutation methods: do not call
append()or assign toservers[0]. Build a new tuple, or choose a list if the collection needs to change. - Immutability is not recursive: a tuple can contain a mutable object such as a list. The tuple’s reference to that object is fixed, but the object’s own contents may still change.
For most scripts, start with direct iteration and add enumerate() or unpacking only when the task requires it. All examples here are local Python operations and require no access to a hosting account.
Related guides
How to Deploy a FastAPI App with Gunicorn and Nginx
Deploy FastAPI behind Nginx with Gunicorn and systemd. Separate application packages, check HTTPS and verify worker replacement and application health.
PythonLearn How to Modify Python Dictionary Values Easily
Learn how to modify Python dictionary values effectively with various methods, including direct assignment, update(), and comprehensions, along with common mistakes to...
PythonPython Set Copy Tutorial: Avoid Common Mistakes and Data Errors
Learn how to copy sets in Python safely and efficiently while avoiding common mistakes. Explore methods like copy(), set(), and deepcopy().
PythonDifferent Methods to Loop Through Sets in Python (Beginner-Friendly Guide)
Learn diverse methods to loop through sets in Python, including practical examples and use cases, ideal for beginners looking to master set operations.
