Control flow · Lesson 5 of 18 · 18 min
Loops and iteration
for, while, range, zip, and the iterator protocol.
- Iterate collections without index arithmetic
- Use enumerate, zip, and range fluently
- Know how for really works
for is not a C for
`for item in collection:` asks the collection for an iterator (`iter(collection)`), then repeatedly calls `next` until `StopIteration`. Anything that implements that protocol is iterable: lists, strings, files, dicts, generators, your own classes.
You almost never need `for i in range(len(xs))`. Use `for x in xs` to see values, `for i, x in enumerate(xs)` when you also need the index, and `for a, b in zip(xs, ys)` to walk two sequences together.
letters = ["a", "b", "c"]
for i, ch in enumerate(letters, start=1):
print(i, ch)
print(list(zip("abc", [10, 20, 30])))
print(list(range(3, 10, 2)))
for line in "alpha\nbeta\n".splitlines():
print("line:", line)while, else, and early exits
`while` is for loops where the end condition is not 'the collection is exhausted' — waiting, retrying, reading until a sentinel.
`break` leaves the loop. `continue` skips to the next iteration. Python has `for/else` and `while/else`: the `else` runs if the loop did not `break`. It is the right shape for 'search, else not found'.
def first_even(nums):
for n in nums:
if n % 2 == 0:
return n
return None
def first_even_else(nums):
for n in nums:
if n % 2 == 0:
break
else:
return None
return n
print(first_even([1, 3, 4, 6]), first_even_else([1, 3, 5]))Check yourself
Quiz
1.What does `list(zip('ab', [1, 2, 3]))` produce?
2.The else clause on a for-loop runs when:
3.`for x in xs` is equivalent to iterating:
Practice
Exercise
Write `index_of(items, target)` that returns the first index of target, or -1 if it is missing. Use enumerate. Do not use list.index.
Tutor
Ask a question about this lesson. Answers are generated on demand and capped so the session stays focused.