Bitpath

Lesson 2 · Unit 08

Generators and type hints

Values made one at a time, and notes about types

13 exercisesabout 3 min

What you practise

  • yield, values made one at a time, pipelines that never build a list, type hints and what reads them

Try a question from this lesson

Pick one

yield hands one value to the loop and pauses the function right there, until the loop asks for the next one. What does this program show?

Python
def countdown(n):
    while n > 0:
        yield n
        n -= 1

for x in countdown(3):
    print(x)
Hint

After each value, the function carries on from the line after the yield.

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

Generators

A function with yield in it is a generator function.

Calling it runs none of its code. It gives back a generator: a thing that makes values on request. next asks for one value, and a for loop keeps asking until the function ends.

Python
def pair():
    yield "a"
    yield "b"

gen = pair()         # nothing runs yet
print(next(gen))     # a
print(next(gen))     # b
print(list(pair()))  # ['a', 'b']

Concept

Pipelines that never build a list

A comprehension in round brackets is a generator too: nothing is worked out until something asks.

Feed one generator into the next and you have a pipeline. Each value travels through every step before the next value is even made, so no list is ever built, however much data there is.

Python
nums = [1, 2, 3, 4]

squares = (n * n for n in nums)
big = (s for s in squares if s > 3)

print(sum(big))  # 4 + 9 + 16 = 29

Concept

Type hints

A type hint is a note about what type a value should be. After a parameter comes a colon and a type. After the brackets, an arrow and the type of the result.

Python does not check hints when the program runs. Editors and checking tools read them and warn you before you run anything.

Python
def average(nums: list[float]) -> float:
    return sum(nums) / len(nums)

count: int = 0
name: str = "Ada"

print(average([1.0, 2.0]))  # 1.5

9 more exercises in the app

  • 2× type the answer
  • 3× multiple choice
  • 1× fill the blanks
  • 1× true or false
  • 1× match the pairs
  • 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