Skip to content
Silver 8 min read · Laziness 3 practice problems ↓

Iterators, yield from and itertools

Every for loop you have written used an iterator. This lesson opens the loop up one step at a time, so generators, yield from and itertools stop feeling like magic.

Foundations · Python for data engineers · Silver · Functions and laziness, lesson 3 of 3

Read first: Generators and lazy evaluation (skip if you know it)

In plain words first

Two words do all the work in this lesson. They sound alike, so start with a picture:

Iterable: the book

Something you can read from start to end, as often as you like: a list, a string, a dict, a range, a file.

Iterator: the bookmark

A marker that remembers where you are in one reading. It only moves forward, and once it reaches the end it is used up.

You can put many bookmarks in one book, one per reader. That is why two loops over the same list never get in each other's way: each loop gets its own iterator.

What a for loop really does

for name in riders: looks like one step, but Python does three small things for you. Click through them:

Step 1 · get a bookmark

iter(riders) asks the list for a fresh iterator, placed before the first item. The list itself does not change.

The command

it = iter(riders)

Step 2 · read one item

next(it) returns the item under the bookmark, "Kiran", and moves the bookmark forward by one.

The command

next(it)  # "Kiran"

Step 3 · read the next

Another next(it) returns "Arun". The iterator remembers that it already handed out "Kiran".

The command

next(it)  # "Arun"

Step 4 · the end

Nothing is left, so next(it) raises StopIteration. A for loop catches this for you and simply stops. That is the whole mechanism.

The command

next(it)  # raises StopIteration

Here are the same steps as code you can run yourself:

Python · the loop, written out
riders = ["Kiran", "Arun"]
it = iter(riders)
print(next(it))
print(next(it))
try:
    next(it)
except StopIteration:
    print("done")

Output from a real run

Kiran
Arun
done

Behind iter() and next() are two special methodsmethod: A function defined inside a class and called on an object, like name.upper() or order.total(). Learn more →. You only need them when you write your own iterable class, but their names come up in interviews:

You writePython callsMeaning
iter(x)x.__iter__()Give me a fresh iterator. Anything that has it is an iterable.
next(it)it.__next__()Give me the next item, or raise StopIteration. Anything that has it is an iterator.
for v in x:bothiter() once, then next() until StopIteration.

An iterator is used up after one pass

This is the surprise that catches most beginners. A list can be read again and again, but an iterator cannot: once its bookmark is at the end, it stays there.

Python · the same sum, twice
prices = [120, 80, 45]
it = iter(prices)
print(sum(it))
print(sum(it))
print(sum(prices))
print(sum(prices))

Output from a real run

245
0
245
245

The second sum(it) is 0, not an error: nothing was left. Generatorsgenerator: A function that uses yield. Calling it does not run it: it returns an iterator that runs the function bit by bit, one item per next(). Learn more →, open files and the results of map, filter and zip are iterators too, so looping over one twice silently gives nothing the second time:

Python · a generator is single-use
def big_orders(amounts):
    for a in amounts:
        if a > 100:
            yield a


orders = big_orders([120, 80, 450, 300])
print("first pass:", list(orders))
print("second pass:", list(orders))

Output from a real run

first pass: [120, 450, 300]
second pass: []
Tip: Need the values twice? If they are few, keep them in a list: orders = list(big_orders(...)). If they are many, call the generator function again for each pass, which builds a new iterator each time.

Your own class you can loop over again

To make your own object loop-able, give it an __iter__ method, written as a generator (with yield). Every loop calls it again and gets a fresh iterator, so the object behaves like a list, not a used-up iterator:

Python · a re-iterable range of delivery slots
class Slots:
    def __init__(self, start, end, step):
        self.start, self.end, self.step = start, end, step

    def __iter__(self):
        t = self.start
        while t < self.end:
            yield t
            t += self.step


lunch = Slots(12, 14, 1)
print("first loop:", list(lunch))
print("second loop:", list(lunch))  # a fresh generator each time
print([(a, b) for a in lunch for b in lunch])

Output from a real run

first loop: [12, 13]
second loop: [12, 13]
[(12, 12), (12, 13), (13, 12), (13, 13)]

The last line is two loops over lunch at the same time, nested. It works because each loop got its own iterator, like two readers with two bookmarks.

yield from: hand over another iterable

Inside a generator, yield from other means "give the caller every item of other, one by one, then carry on". It is a shorter way to write a small for loop. These two generators do exactly the same:

Python · yield from replaces an inner loop
def with_loop(groups):
    for g in groups:
        for item in g:
            yield item


def with_yield_from(groups):
    for g in groups:
        yield from g


groups = [["tea", "coffee"], ["samosa"]]
print(list(with_loop(groups)))
print(list(with_yield_from(groups)))

Output from a real run

['tea', 'coffee', 'samosa']
['tea', 'coffee', 'samosa']

Where it really shines is a generator that calls itself. A menu can have sections inside sections, to any depth. The generator yields plain items, and for a nested list it hands over everything the inner call yields:

Python · walk a nested menu lazily
def items(menu):
    for entry in menu:
        if isinstance(entry, list):
            yield from items(entry)
        else:
            yield entry


menu = ["thali", ["dosa", ["masala", "plain"]], "lassi"]
print(list(items(menu)))

Output from a real run

['thali', 'dosa', 'masala', 'plain', 'lassi']
Watch out: A string is an iterable of one-character strings, and a one-character string iterates to itself. Code that recurses into "anything iterable" must treat str and bytes as plain items, or it recurses forever. The example above avoids this by testing for list only.

itertools, one function at a time

itertools is a standard-library module of small building blocks. They work on any iterable and stay lazylazy: Computed only when asked for, one item at a time, instead of all at once up front. Saves memory on large data. Learn more →: they produce one item at a time instead of building a whole list. These five cover most data engineering code.

islice: take the first few

Slicingslice: A piece of a list or string, xs[start:stop:step]. It always builds a new list; xs[::-1] is a reversed copy. Learn more → with [:3] needs a list. islice takes the first items of any iterator, even an endless one:

Python · the first three ids of an endless stream
from itertools import islice


def order_ids():
    n = 1000
    while True:
        n += 1
        yield n


print(list(islice(order_ids(), 3)))

Output from a real run

[1001, 1002, 1003]

chain: several iterables as one

Python · two days of orders, one loop
from itertools import chain

monday = ["o1", "o2"]
tuesday = ["o3"]
print(list(chain(monday, tuesday)))

Output from a real run

['o1', 'o2', 'o3']

accumulate: running totals

Python · revenue so far, day by day
from itertools import accumulate

daily_revenue = [500, 300, 700]
print(list(accumulate(daily_revenue)))

Output from a real run

[500, 800, 1500]

pairwise: each item with the next one

Python · minutes between logins
from itertools import pairwise

login_minutes = [1, 4, 9]
print([b - a for a, b in pairwise(login_minutes)])

Output from a real run

[3, 5]

groupby: runs of the same key

groupby groups items that sit next to each other with the same key. It does not look ahead, so unsorted data gives you the same key several times. Sort by the key first:

Python · unsorted, then sorted
from itertools import groupby

cities = ["Pune", "Pune", "Delhi", "Pune"]
print([(city, len(list(rows))) for city, rows in groupby(cities)])
print([(city, len(list(rows))) for city, rows in groupby(sorted(cities))])

Output from a real run

[('Pune', 2), ('Delhi', 1), ('Pune', 1)]
[('Delhi', 1), ('Pune', 3)]

Putting two of them together: sort events by user, group them, and measure the gaps between each user's events.

Python · groupby needs sorted input; pairwise gives gaps
import itertools

events = [("asha", 1), ("asha", 4), ("ben", 2), ("asha", 9)]
events.sort(key=lambda e: e[0])
for user, rows in itertools.groupby(events, key=lambda e: e[0]):
    times = [t for _, t in rows]
    gaps = [b - a for a, b in itertools.pairwise(times)]
    print(user, "| times:", times, "| gaps:", gaps)

Output from a real run

asha | times: [1, 4, 9] | gaps: [3, 5]
ben | times: [2] | gaps: []

For reference, the whole set at a glance:

FunctionWhat it doesTypical use
islice(it, n)The first n items (or a slice) of any iteratorPreview a stream, take a page
chain(a, b, ...)One iterator over severalRead several files as one
accumulate(it)Running totals (or any running function)Cumulative revenue
pairwise(it) (3.10+)Consecutive pairs (a, b), (b, c)...Gaps between events
groupby(it, key)Runs of consecutive items with the same keyGroup sorted records
batched(it, n) (3.12+)Tuplestuple: An ordered, immutable sequence like ("Pune", 2026). Because it cannot change, it can be a dict key; use it for small fixed records. Learn more → of n itemsBulk inserts

When to reach for this

  • Reading a big file: a file is an iterator, so for line in f holds one line in memory, not the whole file.
  • Processing records in steps: chain generators (read, clean, filter), with no list built between steps.
  • Peeking at a stream: islice takes the first few items.
  • Grouping sorted data: groupby on records already sorted by key, such as rows from ORDER BY user_id.
  • Your own collection: write __iter__ as a generator to loop over it any number of times.

Common mistakes

  • Looping over a generator twice — The second loop is silently empty, with no error. Keep the values in a list, or call the generator function again.
  • groupby on unsorted data — It groups only consecutive equal keys. Sort by the key first.
  • Returning self from __iter__ by habit — The object becomes single-use, like an iterator. Make __iter__ a generator instead.
  • Recursing into strings — Infinite recursion. Treat str and bytes as plain items.

Key takeaways

  • An iterable is the book; an iterator is a bookmark that only moves forward.
  • A for loop calls iter() once, then next() until StopIteration.
  • Iterators, generators and open files are used up after one pass; lists are not.
  • Write __iter__ as a generator for classes you can loop over again.
  • yield from hands over another iterable; itertools gives lazy slicing, chaining, running totals, pairs and grouping.

Interview prep

THE QUESTION

"What is the difference between an iterable and an iterator?"

An iterable can produce iterators: it has __iter__, like a list, dict or file. An iterator is the cursor: it has __next__, remembers its position, and is exhausted after one pass; its __iter__ returns itself. A for loop calls iter() on the iterable and next() until StopIteration. It matters when designing classes: if __iter__ returns self, nested loops and second passes break, so I usually write __iter__ as a generator function.

Avoid: "iterables and iterators are the same thing". An iterator is a single-use cursor; an iterable produces fresh ones.

Follow-ups · answer out loud, then open

Follow-up"Why does itertools.groupby need sorted input?"
It groups only consecutive items with equal keys, streaming, without a dict. Unsorted input produces several groups for the same key. Sort by the same key first, or use a dict when the data fits.
Scenario"Read 300 daily CSV files as one stream of rows."
itertools.chain.from_iterable over a generator that opens each file and yields its rows. Files open one at a time, rows stream, and downstream code sees a single iterable.
Trap"If __iter__ returns self, nested loops over the object work."
Both loops share one cursor: the inner loop exhausts it and the outer loop ends early. Return a new iterator each time, usually by writing __iter__ as a generator.

Check yourself

4 questions

What ends a for loop over an iterator?

Show the answer

It raises StopIteration. next() raises StopIteration when there are no more items, and the for loop catches it.

it = iter([1, 2]), then sum(it) twice. What does the second call return?

Show the answer

0. The first sum used the iterator up, so the second one adds nothing.

itertools.groupby([1, 1, 2, 1]) produces how many groups?

Show the answer

3. Consecutive runs: [1, 1], [2], [1].

A class whose __iter__ is a generator function can be looped over...

Show the answer

any number of times. Each iter() call starts a new generator.

Practise this

Problems that use this, graded on hidden tests

Keep going

Up next · new module: Classes and robust code · 4 min read
Classes, properties and dataclasses
Invariants, validated and read-only attributes, alternate constructors and record types.

Related lessons

Previous: Generators and lazy evaluation

Primary sources: Iterator types · itertools