Sub topic 10
When to Use while and When to Use for
This chapter assumes you can write a basic while loop and use break and continue. It also assumes you know for item in sequence, range(), and if statements. Both loops repeat code, so the question is which one fits a given problem.
The working model
The two loops differ in what controls the repetition.
- A
forloop walks through a collection of items that already exists. Python decides when to stop: the loop ends when the items run out. - A
whileloop checks a condition before each pass. You decide when to stop, by changing state so the condition becomes false.
Ask one question: "Do I know what I am looping over before the loop starts?" If you do, use for. If the loop runs until something happens, use while.
Same job, two loops
Both loops can print every name in a list. The while version needs more code, and each extra line is a place to make a mistake.
names = ["Ada", "Grace", "Linus"]
for name in names:
print(name)
i = 0
while i < len(names):
print(names[i])
i += 1The while version needs a starting index, a condition, and an update. If you forget i += 1, the loop never ends. The for version has none of these risks, so prefer it here.
When while is the right tool
Use while when the number of passes depends on values computed inside the loop. This function repeats until its guess is close enough, and nobody can say in advance how many passes that takes.
def sqrt_newton(x, tolerance=1e-9):
guess = x / 2
while abs(guess * guess - x) > tolerance:
guess = (guess + x / guess) / 2
return guess
print(round(sqrt_newton(2), 6))This prints 1.414214. The condition describes the goal ("not close enough yet"), and the body moves toward it. range() cannot express this, because the step depends on the previous result.
Other good fits for while:
- Reading input until the user types a quit word.
- Retrying an operation until it succeeds or you run out of attempts.
- Processing a queue that grows while you work through it.
- Reducing a number, such as
while n > 0:when summing digits.
Common errors
Using while with a manual index
Writing while i < len(items) to visit every item is the most common beginner pattern. It works, but for item in items is shorter and cannot go out of range. If you also need the position, use for i, item in enumerate(items).
Expecting a for loop to follow changes to its variable
Assigning to the loop variable inside a for loop does not change what comes next. Python takes the next value from the iterable on the following pass.
for i in range(5):
print(i)
i = 10This still prints 0 to 4. If you need to jump ahead or step back, you need a while loop with your own counter.
Removing items from a list while looping over it
A for loop tracks a position in the list. If you shorten the list, items shift left and the loop skips one.
nums = [1, 2, 2, 3]
for n in nums:
if n == 2:
nums.remove(n)
print(nums)This prints [1, 2, 3], and one 2 is still there. The loop removed the first 2, and the second 2 slid into the slot the loop had already passed. When the removal depends on the current contents, a while loop states the intent directly:
nums = [1, 2, 2, 3]
while 2 in nums:
nums.remove(2)
print(nums)This prints [1, 3]. A list comprehension such as [n for n in nums if n != 2] also works, and it is often the better choice.
Using while True when the condition is known
while True with break is right for event-driven loops. If you can write the stopping rule as a plain condition at the top, write it there. A reader can then see how the loop ends without hunting for break.
Quick comparison
| Situation | Better choice | Reason |
|---|---|---|
| Visit every item in a list | `for` | Python handles the stopping |
| Repeat exactly 10 times | `for` with `range(10)` | The count is known |
| Repeat until the user quits | `while` | The count is unknown |
| Converge on a value | `while` | The step depends on earlier results |
| Change the step size as you go | `while` | `range()` has a fixed step |
| Remove items based on current contents | `while` or a comprehension | Avoids skipping items |
What carries over
The loop else clause, break, and continue work the same way in both loops. The else block runs when the loop finishes without a break. In a for loop that means the items ran out. In a while loop it means the condition became false.
Exercise
You need to add up the digits of a positive integer, such as 4821, without converting it to a string. Which loop fits, and what does the code look like?
Show answer
Use while, because the number of digits is not known up front and the loop ends when the number reaches 0. For example: n = 4821; total = 0; while n > 0: total += n % 10; n //= 10. After the loop, total is 15.
Exercise
A for loop over range(len(items)) removes items from a list with items.pop(i) and sometimes raises IndexError. Why does it happen, and how do you fix it?
Show answer
range(len(items)) is fixed when the loop starts, but each pop makes the list shorter, so later indexes no longer exist. Fix it by using a while loop with your own index that only advances when nothing is removed, or by building a new list with a comprehension.