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
On this page
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
Iterator: the bookmark
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
next(it) returns "Arun". The iterator remembers that it already handed out "Kiran".The command
next(it) # "Arun"
Step 4 · the end
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:
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 write | Python calls | Meaning |
|---|---|---|
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: | both | iter() 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.
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:
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: []
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:
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:
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:
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']
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:
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
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
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
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:
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.
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:
| Function | What it does | Typical use |
|---|---|---|
islice(it, n) | The first n items (or a slice) of any iterator | Preview a stream, take a page |
chain(a, b, ...) | One iterator over several | Read 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 key | Group 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 items | Bulk inserts |
When to reach for this
- Reading a big file: a file is an iterator, so
for line in fholds 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:
islicetakes the first few items. - Grouping sorted data:
groupbyon records already sorted by key, such as rows fromORDER 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?"
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?"
Scenario"Read 300 daily CSV files as one stream of rows."
Trap"If __iter__ returns self, nested loops over the object work."
Check yourself
4 questionsWhat 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 readClasses, properties and dataclasses
Invariants, validated and read-only attributes, alternate constructors and record types.
Related lessons
Generators and lazy evaluationPython for data engineers · 7 min read
Dunder methods and abstract classes
Previous: Generators and lazy evaluation
Primary sources: Iterator types · itertools