PyForge ยท Python practice library
All topics

Topic 15 of 17

Generators & Iterators

Lazy evaluation with yield, generator expressions, and itertools.

__iter__ / __next__
yield
Generator expressions
itertools

Basic

1 program

Program 1

Simple generator

Basic

yield values one at a time.

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

for x in countdown(5):
    print(x)

Intermediate

2 programs

Program 1

Generator expression

Intermediate

Like list comp but lazy.

python
total = sum(x * x for x in range(1, 1_000_001))
print(total)

Program 2

Fibonacci generator

Intermediate

Infinite sequence, take what you need.

python
def fib():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

gen = fib()
print([next(gen) for _ in range(10)])

Advanced

1 program

Program 1

itertools.groupby

Advanced

Group adjacent equal items.

python
from itertools import groupby

data = "aaabbcaaa"
for key, group in groupby(data):
    print(key, len(list(group)))