15.1 Loops and Comprehensions
Process collections without duplicating work.
Before you start
Work through the earlier fundamentals chapters. Use a Python 3 interpreter and run each example locally.
Core concepts
A for loop visits an iterable’s items. range(n) yields integers from zero up to, but excluding, n. Use enumerate() when you need both an index and a value. A while loop repeats while a condition holds; make sure it can terminate.
break stops the loop and continue skips to the next iteration. A comprehension creates a new collection; prefer a normal loop when the body needs multiple steps or error handling.
Worked example
servers = ["web-01", "db-01", "web-02"]
web_servers = [name for name in servers if name.startswith("web-")]
for number, name in enumerate(web_servers, start=1):
print(number, name)
Mini lab
From ports [22, 80, 443, 8080], collect only ports greater than 100. Expected: [443, 8080]. Repeat with an empty list.
Hint
Start with the smallest input. Print intermediate values while exploring, then replace those prints with checks of the expected result.Show a solution
ports = [22, 80, 443, 8080]
selected = [port for port in ports if port > 100]
assert selected == [443, 8080]
assert [port for port in [] if port > 100] == []
print(selected)
Knowledge check
Does range(3) include the number 3?
Check your answer
No. It produces 0, 1, and 2.Common mistake
Avoid removing items from a list while iterating over it. Build a filtered collection instead.
Completion checklist
- Run the example and explain its output.
- Complete the mini lab without copying the solution.
- Test an edge case and explain how the code handles it.
- Answer the knowledge check in your own words.
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form