Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

PY
Python
0/14 completed
Beginner
Hello PythonVariables and typesWorking with stringsConditions and loopsFunctions
Intermediate
Lists, tuples, dicts and setsFiles and exceptionsModules and the standard library
Advanced
Classes and OOPIterators and generatorsDecorators and context managers
Pro
Async PythonTesting and type hintsVirtual environments, packages and real projects
Tracks / Python / Advanced

Iterators and generators

Every for loop in Python uses the iterator protocol. Understanding it unlocks generators: functions that produce values one at a time, using almost no memory, even for millions of items or endless streams.

How a for loop really works

An iterable is anything you can loop over (lists, strings, dicts, files…). iter() gets an iterator from it, and next() asks the iterator for the next value until it raises StopIteration:

Python · editable

A for loop does exactly this, and stops quietly at StopIteration.

Generators: functions that yield

A function containing yield is a generator function. Calling it doesn't run the body. It returns a generator that runs step by step, pausing at each yield:

Python · editable

Why generators matter: laziness

A list holds every value in memory at once. A generator produces each value only when asked:

Python · editable

That makes generators ideal for large files, database results, and data pipelines.

Infinite sequences

Since values are produced on demand, a generator can go on forever, and you take as many as you need:

Python · editable

Building pipelines

Chain generators together; each item flows through every step before the next one starts. Here's a log analyser that would work just as well on a 10 GB file:

Python · editable

yield from

yield from hands over to another iterable, which is handy for recursion:

Python · editable

Making your own iterable class

Give a class an __iter__ method (it can simply be a generator):

Python · editable

Tools that work with any iterable

Python · editable

A generator can only be used once

Python · editable

If you need the values again, make a new generator or store them in a list.

Practice

  1. Write a generator evens(limit) that yields even numbers up to limit.
  2. Write a generator read_numbers(lines) that skips blank lines and lines starting with #, and yields the remaining lines as ints. Sum the result.
  3. Using itertools.islice and your own generator, print the first 10 prime numbers.
Python · editable
✎ Check your understanding

1.What happens when you call a generator function?

2.What's the difference between [x*x for x in data] and (x*x for x in data)?

3.What does list(gen) return the second time on the same generator?

← Classes and OOP