Skip to content

Python Loops: for, while, break, continue, and enumerate

  • How to iterate over sequences and other iterables with for.
  • How to generate and loop over number ranges with range().
  • How to write while loops and control them with break and continue.
  • How to pair values with their positions using enumerate() and zip().
  • How nested loops work, and when to avoid them.
  • How Python’s loop else clause works and when it is useful.
  • How to choose between for and while for a given task.
  • Python 3.9 or newer installed (python --version).
  • Familiarity with variables, lists, and strings.

Step 1 — Iterating over iterables with for

Section titled “Step 1 — Iterating over iterables with for”

A for loop walks through the items of any iterable — a list, tuple, string, dict, set, or anything that can produce one item at a time. Each iteration binds the loop variable to the next item. You almost never need a manual counter in Python because the loop gives you the item directly.

orders = ["ORD-001", "ORD-002", "ORD-003"]
for order_id in orders:
print(f"Processing {order_id}")
# Processing ORD-001
# Processing ORD-002
# Processing ORD-003

Iterating over a dict walks its keys by default; use .items() to get both the key and the value. Strings iterate one character at a time.

order = {"id": "ORD-001", "customer": "BensonCo", "amount": 149.99}
for key, value in order.items():
print(f"{key} = {value}")
# id = ORD-001
# customer = BensonCo
# amount = 149.99
for char in "ORD-001":
print(char, end=" ")
# O R D - 0 0 1

Verify: Add print("done") after the loop. It runs exactly once, after all items are processed, which confirms the loop completed normally.

range() produces a sequence of numbers on demand without building a list in memory. range(n) yields 0 through n - 1, range(a, b) yields a through b - 1, and range(a, b, step) lets you skip or count backward. Use it when the iteration is “do this N times” or when you need the index itself.

# Three months of data: months 1, 2, 3
for month in range(1, 4):
print(f"Month {month}")
# Month 1
# Month 2
# Month 3
# Even line-item numbers only, stepping by 2
for line_no in range(2, 11, 2):
print(line_no)
# 2
# 4
# 6
# 8
# 10

Verify: Print list(range(1, 4)). It should show [1, 2, 3], confirming range stops before the end value.

A while loop runs as long as its condition is true. Use it when you do not know how many iterations you need up front, such as retrying a flaky network call or draining a queue. The condition is checked before each iteration, so the body may run zero times.

retries = 0
max_retries = 3
connected = False
while not connected and retries < max_retries:
print(f"Attempt {retries + 1}")
# pretend the call usually fails until the third try
retries += 1
if retries == 3:
connected = True
print("connected" if connected else "gave up")
# Attempt 1
# Attempt 2
# Attempt 3
# connected

Verify: Change max_retries to 0. The body should never run and the program should print gave up, which confirms the loop is guarded and cannot spin forever.

Step 4 — Controlling flow with break and continue

Section titled “Step 4 — Controlling flow with break and continue”

break exits the loop immediately. continue skips the rest of the current iteration and jumps to the next one. Both work with for and while. Use break to stop early when you have found what you need, and continue to skip items that do not interest you.

# Stop at the first shipped order
order_ids = ["ORD-001", "ORD-002", "ORD-003"]
statuses = ["pending", "pending", "shipped"]
for i in range(len(order_ids)):
if statuses[i] == "shipped":
print(f"First shipped order is {order_ids[i]}")
break
# First shipped order is ORD-003
# Skip pending orders, process the rest
for order_id, status in zip(order_ids, statuses):
if status == "pending":
continue
print(f"Handling non-pending {order_id} ({status})")
# Handling non-pending ORD-003 (shipped)

Verify: Remove the break and confirm the loop now prints a match for every shipped order instead of just the first one. That confirms break was what stopped the scan early.

Step 5 — Pairing items with enumerate() and zip()

Section titled “Step 5 — Pairing items with enumerate() and zip()”

enumerate() yields (index, value) pairs so you avoid tracking a counter by hand. zip() walks two or more iterables in lockstep, stopping at the shortest one. Together they replace the common for i in range(len(...)) pattern with clearer code.

items = ["keyboard", "mouse", "monitor"]
for index, name in enumerate(items, start=1):
print(f"Line {index}: {name}")
# Line 1: keyboard
# Line 2: mouse
# Line 3: monitor
quantities = [2, 5, 1]
prices = [49.99, 19.99, 299.00]
for qty, price in zip(quantities, prices):
print(f"${qty * price:.2f}")
# $99.98
# $99.95
# $299.00

Verify: Add a fourth quantity but only three prices. The loop should still print exactly three lines because zip stops at the shortest input.

A loop inside a loop lets you process every combination of two sequences, such as every order against every shipping zone. Nested loops are clear but expensive: the total work is the product of the lengths, so a million-item outer loop times a thousand-item inner loop is a billion iterations. When you find yourself nesting three or more levels, reach for a dict lookup or a comprehension instead.

orders = ["ORD-001", "ORD-002"]
zones = ["west", "east", "central"]
for order_id in orders:
for zone in zones:
print(f"{order_id} -> {zone}")
# ORD-001 -> west
# ORD-001 -> east
# ORD-001 -> central
# ORD-002 -> west
# ORD-002 -> east
# ORD-002 -> central

Verify: The output should have exactly len(orders) * len(zones) lines, here six. Counting the printed lines confirms every combination was visited once.

Python gives loops an else block that runs only when the loop finishes normally, without hitting break. This is a Python-specific feature that removes the need for a “found” flag. It is most useful inside a function that searches for something: break when you find it, and put the “not found” handling in else.

order_ids = ["ORD-001", "ORD-002", "ORD-003"]
target = "ORD-009"
for order_id in order_ids:
if order_id == target:
print(f"Found {target}")
break
else:
# runs only because the loop never hit break
print(f"{target} is not in the list")
# ORD-009 is not in the list

Verify: Set target = "ORD-002" and run again. The else block should not print this time, because break ran on the match.

Save as loops_demo.py and run with python loops_demo.py (Python 3.9+):

"""OrdersPortal: process pending orders, retry shipping, and report."""
orders = [
{"id": "ORD-001", "status": "pending", "items": ["keyboard", "mouse"]},
{"id": "ORD-002", "status": "shipped", "items": ["monitor"]},
{"id": "ORD-003", "status": "pending", "items": ["cable", "adapter", "stand"]},
]
# Ship every pending order, retrying up to 3 times each
for order in orders:
if order["status"] != "pending":
continue
attempts = 0
while attempts < 3:
attempts += 1
print(f"{order['id']}: shipping attempt {attempts}")
if attempts == 3: # pretend the carrier accepts on the last try
order["status"] = "shipped"
break
# Count line items across all orders with enumerate for readable line numbers
total_items = 0
for line_no, order in enumerate(orders, start=1):
total_items += len(order["items"])
print(f"Line {line_no}: {order['id']} has {len(order['items'])} item(s)")
print(f"All orders: {orders}")
print(f"Total line items: {total_items}")
ORD-001: shipping attempt 1
ORD-001: shipping attempt 2
ORD-001: shipping attempt 3
ORD-003: shipping attempt 1
ORD-003: shipping attempt 2
ORD-003: shipping attempt 3
Line 1: ORD-001 has 2 item(s)
Line 2: ORD-002 has 1 item(s)
Line 3: ORD-003 has 3 item(s)
All orders: [{'id': 'ORD-001', 'status': 'shipped', 'items': ['keyboard', 'mouse']}, {'id': 'ORD-002', 'status': 'shipped', 'items': ['monitor']}, {'id': 'ORD-003', 'status': 'shipped', 'items': ['cable', 'adapter', 'stand']}]
Total line items: 6
  • while True: with no reliable exit. If the condition that should trigger break never becomes true, the loop runs forever. Add an explicit, bounded condition or a maximum-iteration guard.
  • Modifying a list while iterating over it. Adding or removing items during iteration shifts indices and skips or duplicates items. Iterate over a copy: for x in list(my_orders):.
  • Using for i in range(len(seq)): just to index. Prefer for item in seq: for the value, or enumerate(seq) when you also need the index.
  • Forgetting zip stops at the shortest iterable. Mismatched lengths silently drop the extra items. Use itertools.zip_longest when you need to keep the extras.
  • Confusing else on a loop with else on if. A loop else runs when the loop completes without break, not when the condition is false.

Reach for for when you know what you are walking over — a collection or a fixed range of numbers. Reach for while when the number of repetitions depends on a condition you check each time, such as retrying until success or draining a queue. If you can write the loop as for x in iterable:, you usually should.

  • Conditionals — branching with if, elif, and else
  • Lists — the most common iterable
  • Dictionaries — iterating over keys, values, and items
  • enumerate() — index-and-value pairing in depth
  • zip() — walking iterables in parallel