GCGrowCarrer

Iterators and Generators

Locked

Lesson 19 of 60 · Syntax · Challenging

Finish these first:List Comprehensions →Or pass the tests below to unlock it now.

1

The big idea

An iterator implements iter/next. Generators (yield) produce values lazily, saving memory.

Think of it like this: Think of syntax and expressions like labeled measuring cups in a kitchen: each cup holds a specific kind of ingredient, and operators combine them into a new measurement.
Key words (tap to learn):
2

Read the lesson

An iterator implements __iter__/__next__. Generators (yield) produce values lazily, saving memory.

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

list(countdown(3))   # [3, 2, 1]
sum(x*x for x in range(10))   # generator expression
3

Quick check

Before writing code: What should `list(fib(6))` return when your implementation of Iterators and Generators is working?

4

Your challenge

2 sample tests, 1 hidden

Write generator fib(n) yielding the first n Fibonacci numbers.

Stuck? Get a hint (free)
More learning tools(compare languages, visual guide, related lessons)

Compare with another language

See how Python compares side-by-side with Java.

Visual walkthrough

A diagram, a step-by-step animation, and short captions for Iterators and Generators.

Mastery0%