Sub topic 10
When to use while and when to use for
This chapter assumes you can write a basic while loop and a basic for loop, and that you know what break, continue, and the loop else clause do. Here the question is which loop to pick for a given problem, and why the wrong choice produces bugs.
The deciding question
Both loops repeat a block of code. They differ in what controls the repetition.
- A
forloop repeats once per item of an iterable (a list, a string, a range, a file, a generator). Python's iterator protocol supplies the next item and decides when the items run out. - A
whileloop repeats as long as a condition is true. You supply the state, you update it, and you make sure the condition eventually becomes false.
So ask: can I name the things I will loop over before the loop starts? If yes, use for. If the loop ends because of something that happens during the loop, use while.
Same task, two loops
Printing every item of a list shows how much bookkeeping a while loop adds when a for loop would do.
names = ["Ada", "Grace", "Linus"]
# for: Python advances for you
for name in names:
print(name)
# while: you create, test, and advance the index yourself
i = 0
while i < len(names):
print(names[i])
i += 1The while version has three places to make a mistake: the initial value, the condition, and the update. The for version has none. When a for loop fits, prefer it, because there is less state that can go wrong.
Two related habits are worth dropping:
for i in range(len(names))followed bynames[i]is usually afor name in namesin disguise.- If you need both the position and the item, use
for i, name in enumerate(names).
Where while is the right tool
The number of iterations depends on the data
The Collatz sequence halves even numbers and maps odd numbers to 3n + 1, and it stops at 1. Nobody knows in advance how many steps that takes. The loop runs until a state is reached.
def collatz_steps(n):
steps = 0
while n != 1:
if n % 2 == 0:
n //= 2
else:
n = 3 * n + 1
steps += 1
return steps
print(collatz_steps(6)) # 8The path for 6 is 6, 3, 10, 5, 16, 8, 4, 2, 1, which is 8 steps. No iterable describes that sequence before you compute it.
The loop shrinks a search space
Binary search narrows a range by changing low and high. The loop variable does not walk through items one by one, so for has nothing to iterate over.
def binary_search(items, target):
low, high = 0, len(items) - 1
while low <= high:
mid = (low + high) // 2
if items[mid] == target:
return mid
if items[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
print(binary_search([1, 3, 5, 7, 9, 11], 7)) # 3Each pass must move low or high strictly toward the other, which is the termination argument from the earlier chapter on updating state.
The work list grows while you process it
Graph traversal pulls a node from a queue, and processing that node may add more nodes. The loop ends when the queue is empty. Here the truthiness of the container is the condition.
from collections import deque
def bfs_order(graph, start):
seen = {start}
queue = deque([start])
order = []
while queue:
node = queue.popleft()
order.append(node)
for neighbor in graph[node]:
if neighbor not in seen:
seen.add(neighbor)
queue.append(neighbor)
return order
graph = {"A": ["B", "C"], "B": ["D"], "C": ["D"], "D": []}
print(bfs_order(graph, "A")) # ['A', 'B', 'C', 'D']This example uses both loops. The outer loop is a while because the queue changes. The inner loop is a for because graph[node] is a fixed list of neighbors. Mixing them is normal.
You wait for an event
Reading until the user types "quit", polling until a job finishes, and retrying until a connection succeeds are all event-driven. The while True with break pattern from earlier chapters fits them, as does a while not done: loop with a flag.
Where for is the right tool
If the iterable exists, let Python run it. That covers:
- Lists, tuples, dictionaries, sets, and strings.
- Files, where
for line in filereads lazily and stops at end of file. range(...)for counted repetition, including steps, such asrange(10, 0, -2).- Generators and other iterators.
A for loop also handles continue more safely. In a while loop, continue jumps straight to the condition check and skips anything after it. If the state update sits at the bottom of the body, continue skips it and the loop can run forever. In a for loop, the next item is fetched by the loop itself, so continue cannot skip the advance.
A bounded retry is a for loop
A bounded number of attempts is a counted loop, even though it ends early on success. The loop else clause then reports failure, because it runs only when no break happened.
def try_connect(attempt):
return attempt == 3
for attempt in range(1, 6):
if try_connect(attempt):
print("connected on attempt", attempt)
break
else:
print("gave up")This prints connected on attempt 3. Compare it with a while version, which needs a counter, a flag, and a condition that combines both. The for version expresses "at most five tries" in the loop header. Use while when the number of retries has no fixed cap, for example when you retry until a deadline passes.
Mutating a collection while looping over it
This is the most common reason to leave for for while. A for loop over a list tracks a hidden position. If you remove items from the list during the loop, the later items shift left and the loop skips one.
nums = [1, 2, 2, 3, 4]
for n in nums:
if n % 2 == 0:
nums.remove(n)
print(nums) # [1, 2, 3] (one even number survived)The first 2 is removed at position 1. The second 2 then slides into position 1, and the loop moves on to position 2 and never sees it. Python raises no error. The result is silently wrong.
With a while loop you control the index, so you can advance it only when you did not delete:
nums = [1, 2, 2, 3, 4]
i = 0
while i < len(nums):
if nums[i] % 2 == 0:
del nums[i]
else:
i += 1
print(nums) # [1, 3]For a simple filter, a list comprehension is usually better still: nums = [n for n in nums if n % 2 != 0]. Choose the while version when the removal logic is too involved for a comprehension, or when you must modify the list in place because other code holds a reference to it.
Adding to a list while a for loop iterates over it is a related trap. It can make the loop run longer than you expect. The while queue: pattern above is the safe form of that idea.
Making for behave like while
Sometimes the data comes from a function that you call repeatedly until it returns a sentinel (a special value that means "stop"). The two-argument form iter(callable, sentinel) turns that into an iterable, so a for loop can handle it.
import io
stream = io.StringIO("abcdefgh")
for chunk in iter(lambda: stream.read(3), ""):
print(chunk)This prints abc, def, and gh. It does the same job as the walrus version while chunk := stream.read(3):. Both are correct. The walrus form is more direct when the loop body needs extra conditions, and the iter form is useful when you want to pass the stream to other iterator tools.
Side-by-side comparison
| Question | for | while |
|---|---|---|
| What ends the loop? | The iterable runs out | The condition becomes false, or a `break` runs |
| Who advances the state? | Python | You |
| Risk of an infinite loop | Only with infinite iterables | Any missing or wrong update |
| `continue` skips the advance? | No | Yes, if the update comes after it |
| Safe to remove items from the list being looped over? | No | Yes, with careful index handling |
| Typical use | Collections, files, counted repetition | Searches, events, queues, convergence, shrinking ranges |
Edge cases and gotchas
- Floating-point counters. Adding
0.1ten times gives0.9999999999999999, sowhile x != 1.0never becomes false. Use an integer counter and divide, as infor i in range(11): print(i / 10). If you need awhileloop on floats, use<or<=, or a tolerance such asabs(x - target) > 1e-9. - Infinite iterables in for.
for n in itertools.count()never ends by itself. It needs abreak, just likewhile True. - Reassigning the loop variable. In a
forloop, assigning to the loop variable inside the body does not change the next item. In awhileloop, assigning to the state variable changes the next condition check. Do not carry awhilehabit into aforloop. - Variable after the loop. After a
forloop over an empty iterable, the loop variable is never created. After awhileloop, any variable you initialized beforehand still exists.
Summary of the rule
- Known collection or known count:
for. - Loop ends on a state, event, or converging value:
while. - Collection changes size as you loop:
whilewith careful updates, or build a new collection. - A function called until a sentinel appears:
whilewith the walrus operator, orforwithiter(callable, sentinel).
Exercise
A function must remove every empty string from a list words in place, so that other references to the same list see the change. A teammate wrote for w in words: if w == "": words.remove(w). Explain why it fails for ["a", "", "", "b"], then write a while version that works.
Show answer
After the first empty string at index 1 is removed, the second empty string shifts into index 1, but the for loop's hidden position moves on to index 2, so it never checks the shifted item. The result is ["a", "", "b"]. A correct version advances the index only when nothing was deleted:
i = 0
while i < len(words):
if words[i] == "":
del words[i]
else:
i += 1
For ["a", "", "", "b"] this leaves ["a", "b"]. (words[:] = [w for w in words if w] also works in place.)
Exercise
Which loop fits each task better, and why? (a) Print each line of a text file. (b) Keep halving a number until it is below 1. (c) Try to connect to a server at most 4 times.
Show answer
(a) for, because a file is an iterable of lines and Python stops at the end. (b) while, because the number of halvings depends on the starting value and the loop ends on a condition (while n >= 1: n /= 2). (c) for attempt in range(4) with break on success and an else clause for failure, because the maximum count is known up front.