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
    Foundation builder

    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.
    • itertools is the Swiss-army knife.
    • StopIteration ends iteration.

    Syntax reference

    Visual flow / code:

    python
    import itertools as it
    # Infinite + take first N
    list(it.islice(it.count(1), 5)) # [1,2,3,4,5]
    # Chain iterables
    list(it.chain([1,2], [3,4])) # [1,2,3,4]
    # Group consecutive by key
    data = [("a",1), ("a",2), ("b",3)]
    for k, group in it.groupby(data, key=lambda x: x[0]):
    print(k, list(group))
    # Cartesian product
    list(it.product([1,2], ["a","b"])) # [(1,'a'),(1,'b'),(2,'a'),(2,'b')]

    Execution workflow

    1Iterators & itertools Workflow
    1 / 4

    Step 1

    Iterator: __iter__ + __next__.

    Apply this step while implementing iterators & itertools in real code.

    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 islice instead of slicing big iterables.

    Hands-on exercise

    Interview preparation — practice these questions:

    • Iterator vs iterable?
    • Show 3 itertools functions.
    • What's StopIteration?

    Summary

    In summary: Iter protocol = simple contract. itertools = composable building blocks.

    Ready to mark this lesson complete?Track your journey across the entire course.