Bitpath

Boss lesson · Unit 01

How for works

Iterators, generators and a pipeline that never builds a list

13 exercisesabout 3 min

What you practise

  • Iterables and iterators, iter and next, generators and yield, 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?

Python
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?

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.

Python
it = iter([10, 20])
print(next(it))          # 10
print(next(it))          # 20
print(next(it, "done"))  # done

Concept

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.

Python
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))    # 1

10 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.

One email when Bitpath is ready to try. Nothing else. Privacy