for and while loops

Python · Essentials · 10 min

Loops are how you process collections, files and input one item at a time.

Python's for loop iterates over the items of any iterable — a list, string, dict, file, range — rather than counting an index: for word in words:. To loop a fixed number of times use range: range(5) yields 0..4, range(2, 10, 2) yields 2, 4, 6, 8. The stop value is always excluded.

Resist for i in range(len(items)). Python has better tools:

  • enumerate(items, start=1) gives (index, item) pairs
  • zip(names, scores) walks two iterables in parallel, stopping at the shorter (pass strict=True to raise if lengths differ)
  • reversed(items) and sorted(items) loop backwards or in order

A while loop repeats as long as its condition is truthy. Use it when you don't know the number of iterations in advance, such as retrying until input is valid. while True: with a break is a common, clear pattern.

Inside any loop, break exits immediately and continue skips to the next iteration. Loops can also have an else clause, which runs only if the loop finished without hitting break — useful for search loops ("not found").

Don't add or remove items from a list while looping over it; you'll skip elements. Loop over a copy (for x in items[:]) or build a new list instead.

Example

names = ["Ana", "Ben", "Cy"]
scores = [91, 78, 85]

for i, name in enumerate(names, start=1):
    print(i, name)                 # 1 Ana / 2 Ben / 3 Cy

for name, score in zip(names, scores):
    print(f"{name}: {score}")

for n in range(10, 0, -3):
    print(n, end=" ")              # 10 7 4 1
print()

target = 42
for n in [5, 17, 99]:
    if n == target:
        print("found")
        break
else:
    print("not found")             # not found

count = 0
while count < 3:
    count += 1
print(count)                       # 3

Remember

  • for iterates items directly; use enumerate and zip instead of indexes
  • range(start, stop, step) excludes stop
  • A loop's else runs only when no break happened

Watch out for

  • Modifying a list while iterating over it.

Check yourself

  1. What does `list(range(1, 8, 3))` produce?
  2. When does the `else` block of a `for` loop run?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: docs.python.org/3/tutorial/controlflow.html#for-statements