GICT knowledge base
Python Loops: for, while, break, continue and Loop else
Published
A Python for loop consumes items from an iterable, such as a list, dictionary, range or generator. A while loop repeats while a condition is truthy. Choose based on where the next item comes from, not whether you already know the number of repetitions.
The examples below run independently with Python 3.12.14 and use only local sample data. They do not connect to servers, authenticate users or change files.
Loop over values, keys and positions
Iterate over values directly when you do not need an index. Use enumerate() for a position and value, or items() for dictionary keys and values. A dictionary loop without items() yields keys.
services = ["web", "mail", "dns"]
numbered = []
for position, service in enumerate(services, start=1):
numbered.append(f"{position}: {service}")
ports = {"web": 443, "mail": 587}
pairs = []
for service, port in ports.items():
pairs.append((service, port))
assert numbered == ["1: web", "2: mail", "3: dns"]
assert pairs == [("web", 443), ("mail", 587)]
print(numbered)
A generator can yield values without storing the whole result first. A for loop can consume it even when its eventual length is unknown. Once that particular generator is exhausted, create a new one if you need to repeat the work.
Repeat a fixed number of times with range
range(1, 4) supplies 1, 2 and 3; its stop value is excluded. It is a reusable sequence, not a generator. See the range guide for steps, negative directions and empty ranges.
labels = []
for attempt in range(1, 4):
labels.append(f"attempt-{attempt}")
assert labels == ["attempt-1", "attempt-2", "attempt-3"]
print(labels)
Make a while loop progress toward its exit
The condition is checked before each iteration, so the body may run zero times. Identify exactly what changes the condition. In this countdown, subtracting one prevents an endless loop. A real polling task also needs a timeout and usually a delay; a tight loop should not repeatedly hit a remote service.
remaining = 3
countdown = []
while remaining > 0:
countdown.append(remaining)
remaining -= 1
assert countdown == [3, 2, 1]
assert remaining == 0
print(countdown)
Skip an item with continue
continue skips the rest of the current iteration. In a while loop, update a counter before a path that can continue; otherwise that path may never reach the update. Here, blank entries are ignored without mutating the input list.
entries = [" web ", "", " ", "mail"]
cleaned = []
index = 0
while index < len(entries):
value = entries[index].strip()
index += 1
if not value:
continue
cleaned.append(value)
assert cleaned == ["web", "mail"]
assert entries == [" web ", "", " ", "mail"]
print(cleaned)
Stop with break; use loop else for no match
break leaves the innermost loop. A loop’s else runs when iteration ends normally, including an empty input, rather than through break. A return or exception that leaves the loop also bypasses its else. Notice that else below aligns with for, not if.
def first_large(values, limit):
for value in values:
if value > limit:
result = value
break
else:
result = None
return result
assert first_large([4, 12, 20], 10) == 12
assert first_large([4, 10], 10) is None
assert first_large([], 10) is None
print(first_large([4, 12, 20], 10))
Build a result instead of changing the collection mid-loop
Removing entries from the same list you are traversing can skip entries. Changing a dictionary’s size during traversal can raise an error. Build a separate result when that matches your goal; this also leaves the original available for comparison.
states = {"web": "ready", "mail": "paused", "dns": "ready"}
ready = {}
for service, state in states.items():
if state == "ready":
ready[service] = state
assert ready == {"web": "ready", "dns": "ready"}
assert len(states) == 3
print(ready)
If a loop appears stuck, inspect its condition, every continue path and whether its input can ever finish. If it runs but produces unexpected results, check indentation and where you reset accumulators. For two levels of iteration, see nested loops.
Verification: All six blocks were executed independently, including empty-input and boundary assertions. These are language examples, not a production retry or authentication system. Reference: Python’s for and while statement specification.
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.
