Python Tutorial 0/52 lessons ~6 min read Lesson 37
Iterators & itertools
Any object with iter + next is an iterator.
Course progress0%
Focus
8 guided sections
Practice signal
Examples included
Career prep
Interview Q&A included
Introduction
Any object with __iter__ + __next__ is an iterator. itertools provides production-ready building blocks: chain, islice, groupby, product.
Understanding the topic
Core concepts to understand:
- Iterator:
__iter__+__next__. - Generators are iterators.
itertoolsis the Swiss-army knife.StopIterationends iteration.
Syntax reference
Visual flow / code:
python
import itertools as it# Infinite + take first Nlist(it.islice(it.count(1), 5)) # [1,2,3,4,5]# Chain iterableslist(it.chain([1,2], [3,4])) # [1,2,3,4]# Group consecutive by keydata = [("a",1), ("a",2), ("b",3)]for k, group in it.groupby(data, key=lambda x: x[0]):print(k, list(group))# Cartesian productlist(it.product([1,2], ["a","b"])) # [(1,'a'),(1,'b'),(2,'a'),(2,'b')]
Execution workflow
1Iterators & itertools Workflow
1 / 4Iterator
__iter__ + __next__.
Real-world use
itertools is one of the most underused gems of the stdlib — replaces dozens of lines of manual looping with clear, fast primitives.
Best practices
- Reach for itertools before writing nested loops.
- Use
isliceinstead of slicing big iterables.
Advanced interview questions
Interview Prep
Practice concise answers, then expand each card for the explanation.
1BeginnerQuestionIterator vs iterable?+
Answer
An iterable has an
__iter__ method that returns an iterator, such as a list or string, and can usually be looped many times. An iterator has __next__ and its own __iter__ returning itself; it keeps state and is exhausted after one pass. A for loop calls iter() on the iterable and then next() repeatedly.Follow-up
Is a generator an iterator or an iterable?
2BeginnerQuestionShow 3 itertools functions.+
Answer
itertools.chain(a, b) iterates through several iterables as one sequence. itertools.islice(it, n) takes a slice of any iterator lazily, such as the first n items. itertools.groupby(data, key) groups consecutive items with the same key, so data usually needs sorting first. Others include batched (3.12+), product, and accumulate.Follow-up
Why does
groupby require sorted input?3IntermediateQuestionWhat's StopIteration?+
Answer
StopIteration is the exception an iterator raises from __next__ to say there are no more items; for loops catch it to end the loop. Its value attribute carries a generator's return value. Since PEP 479, a StopIteration that escapes inside a generator body is converted into RuntimeError, so generators should simply return.Follow-up
How does the two-argument form of
next() help?Summary
In summary: Iter protocol = simple contract. itertools = composable building blocks.
Ready to mark this lesson complete?Track your journey across the entire course.