Advanced Python: iterators, generators, and itertools
The iterator protocol, yield, generators, itertools.chain and islice, plus lazy streams and memory. Twenty corrected exercises with fold-out solutions.
Getting started
Home Assistant
Buying
The iterator protocol, yield, generators, itertools.chain and islice, plus lazy streams and memory. Twenty corrected exercises with fold-out solutions.


AI-generated illustration
Some links on this page are affiliate links. The button opens Amazon so you can check today’s price.
In Python, a for loop does not magically walk a list: it asks an iterator — an object that knows how to produce items one by one according to the iterator protocol. Once you understand that mechanism, you can write lazy code that does not load everything into memory, compose data pipelines, and use generators (yield), which sit at the base of many modern APIs.
__iter__ methodAn iterable is anything you can walk with for: lists, tuples, strings, files opened in text mode, and so on. Technically, an iterable exposes __iter__(), which returns an iterator. The iterator exposes __next__() (or next() in Python 3) and raises StopIteration when there are no items left.
it = iter([1, 2, 3])
print(next(it)) # 1
print(next(it)) # 2
Why does this matter? Because two independent for loops on the same iterable often create a new iterator from the iterable, whereas a consumed iterator does not rewind on its own: once it is exhausted, it stays empty.
yieldA generator function uses yield instead of return to pause its execution and hand back a value. On the next call, it resumes after the yield. The object you get back is a generator, which is also an iterator: you do not load a whole list into memory.
def compte_jusqua(n):
i = 0
while i < n:
yield i
i += 1
for x in compte_jusqua(3):
print(x)
Typical uses: reading large files line by line, transformation pipelines, infinite combinators bounded by a business condition.
The syntax (expr for x in it if cond) — parentheses, except when it is the only argument of a function call, where the generator’s parentheses can be omitted. This is an anonymous generator, not a list.
carres = (x * x for x in range(5))
itertools moduleitertools provides efficient iterators combined in C: chain to chain iterables, islice to slice without copying the whole sequence, cycle, repeat, groupby (often after a sort), zip_longest, and more. It is the standard toolbox for composing streams without huge intermediate lists.
from itertools import chain, islice
list(islice(chain([1, 2], [3, 4]), 3))
list(...)) or create the generator again.itertools.groupby groups identical adjacent items: you often sort first with sorted(iterable, key=...).The solutions are hidden by default.
Exercise 1 — Use iter and next on "ab" to print a then b. Easy
it = iter("ab")
print(next(it))
print(next(it))
Exercise 2 — Write a generator pairs(n) that yields the even integers 0, 2, … strictly less than n. Easy
def pairs(n):
i = 0
while i < n:
if i % 2 == 0:
yield i
i += 1
Exercise 3 — A list comprehension of the squares of range(4). Easy
[x * x for x in range(4)]
Exercise 4 — The equivalent generator expression, then list(...) to display it. Easy
list(x * x for x in range(4))
Exercise 5 — Import chain and print list(chain([1], [2, 3])). Easy
from itertools import chain
print(list(chain([1], [2, 3])))
Exercise 6 — Use islice to take the first 3 items of range(100) without building the full list. Easy
from itertools import islice
print(list(islice(range(100), 3)))
Exercise 7 — In one sentence, explain why list(g) then list(g) on the same generator g often gives [] the second time. Easy
# The generator is exhausted after the first walk; the second walk produces nothing.
Exercise 8 — A generator lecture_lignes(chemin) that opens a file with encoding="utf-8" and yields each line without loading the whole file into memory (use open and a loop). Intermediate
def lecture_lignes(chemin):
with open(chemin, encoding="utf-8") as f:
for ligne in f:
yield ligne.rstrip("\n")
Exercise 9 — Use enumerate on a generator of range(3) and print (index, value). Intermediate
for t in enumerate(x for x in range(3)):
print(t)
Exercise 10 — With zip, combine "abc" and [1, 2, 3] into a list of tuples. Intermediate
print(list(zip("abc", [1, 2, 3])))
Exercise 11 — Import zip_longest from itertools with fillvalue=0 and zip [1] with [1, 2, 3]. Intermediate
from itertools import zip_longest
print(list(zip_longest([1], [1, 2, 3], fillvalue=0)))
Exercise 12 — itertools.count(start=10, step=2): take 5 values with islice. Intermediate
from itertools import count, islice
print(list(islice(count(10, 2), 5)))
Exercise 13 — An infinite fibonacci() generator; print the first 8 terms with islice. Intermediate
from itertools import islicedef fibonacci(): a, b = 0, 1 while True: yield a a, b = b, a + b
print(list(islice(fibonacci(), 8)))
Exercise 14 — Give an example where [f(x) for x in huge] is risky for memory, and the generator variant you would prefer. Intermediate
# A list allocates everything at once. A generator (f(x) for x in huge) does not materialize the full sequence.
Exercise 15 — Implement grouper_par_deux(iterable) that yields consecutive tuples (a, b); if the length is odd, ignore the last item or handle it with an option (pick a policy and document it). Hard
def grouper_par_deux(iterable): it = iter(iterable) while True: try: a = next(it) b = next(it) except StopIteration: break yield (a, b)
print(list(grouper_par_deux([1, 2, 3, 4, 5]))) # (5) ignored
Exercise 16 — Use groupby on sorted("abracadabra") to print letter → number of occurrences (adjacent). Hard
from itertools import groupby
for k, g in groupby(sorted("abracadabra")):
print(k, len(list(g)))
Exercise 17 — What is the difference between yield and yield from in a sub-generator? Give a tiny example. Hard
def inner(): yield 1 yield 2def outer(): yield from inner() # delegates without an explicit loop
print(list(outer()))
Exercise 18 — Combine chain.from_iterable with a list of lists [[1, 2], [3]]. Hard
from itertools import chain
print(list(chain.from_iterable([[1, 2], [3]])))
Exercise 19 — Write a generator that merges two sorted iterables into a sorted stream (merge-sort style) for integers; assume the inputs are sorted. Hard
def merge_tri(a, b): ia, ib = iter(a), iter(b) x = next(ia, None) y = next(ib, None) while x is not None and y is not None: if x <= y: yield x x = next(ia, None) else: yield y y = next(ib, None) while x is not None: yield x x = next(ia, None) while y is not None: yield y y = next(ib, None)
print(list(merge_tri([1, 4], [2, 3])))
Exercise 20 — Explain why sum([[1], [2], [3]], []) “flattens” but is inefficient; suggest chain.from_iterable instead. Hard
# sum on lists builds intermediate copies, O(n²). chain.from_iterable is linear and lazy.
from itertools import chain
list(chain.from_iterable([[1], [2], [3]]))
Decorators, wrappers, and functools: add behavior without duplicating code.
Was this page helpful?
Thank you!
What should we improve?
Torn between two models or stuck on a build? Drop us a line and we will get back to you by email.
Cookies and analytics
We use Google Analytics 4 to understand how the site is used (page views, navigation). It is only switched on if you accept. Declining does not stop you using the site. More: cookie settings and privacy policy (in French).