A Generator Function

def count_up_to(n):
    i = 1
    while i <= n:
        yield i
        i += 1

for x in count_up_to(5):
    print(x)
# 1 2 3 4 5

Why Generators?

Generator Expressions

total = sum(x*x for x in range(1_000_000))

Same syntax as a list comp, but with ( ) instead of [ ]. Does not build the full list.

Chaining

nums = (n for n in range(100))
squares = (n*n for n in nums)
evens = (s for s in squares if s % 2 == 0)

Practise this on PyForm โ€” free

PyForm runs Python in your browser with an AI tutor trained for HKDSE. No install, no credit card.

Open PyForm โ†’