Boss lesson · Unit 01
How for works
Iterators, generators and a pipeline that never builds a list
What you practise
- Iterables and iterators,
iterandnext, generators andyield, lazy pipelines that never build a list, the generator that is already used up
Try a question from this lesson
Pick one
The same name is summed twice. What prints?
squares = (n * n for n in range(4))
print(sum(squares), sum(squares))Hint
Round brackets make this a generator, not a list. What is left after the first pass?
Correct answer
14 0
Why
Round brackets make a generator: a one-way cursor that produces each square once. The first sum drains it, so the second sees nothing and returns 0. A list could be walked again; an iterator cannot.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
for is iter() plus next()
for x in obj first calls iter(obj) to get an iterator, then calls next() on it until it raises StopIteration.
An iterable can hand out iterators (a list gives a fresh one each time). An iterator is the cursor itself: it remembers its position and, once at the end, stays empty.
it = iter([10, 20])
print(next(it)) # 10
print(next(it)) # 20
print(next(it, "done")) # doneConcept
Generators pause at yield
A function containing yield does not run when called: it returns a generator, which is an iterator.
Each next() runs the body up to the next yield, hands that value out and freezes, local variables and all. Reaching the end raises StopIteration.
def count_up(n):
print("start")
for i in range(n):
yield i
gen = count_up(2) # prints nothing yet
print(next(gen)) # start, then 0
print(next(gen)) # 110 more exercises in the app
- 1× fill the blanks
- 4× multiple choice
- 4× type the answer
- 1× order the lines
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.