Skip to contentSkip to navigation

Module 13 · Lesson 04

itertools: Building Blocks for Iterators

Use the itertools module's fast, lazy tools: endless count and cycle, islice, chain, accumulate, pairwise and batched, grouping with groupby, and combinations, permutations and product.

  • About 9 minutes
  • Builds on earlier lessons
  • 12-question quiz at the end

What you will learn

  • Endless iterators, safely
  • Join and pair streams
  • Running totals with accumulate
  • Watch steps become totals

Ready-made loop tools

itertools gives fast, lazy building blocks, so many loops become one line.

  • Endless

    count() and cycle() go on for ever. islice() takes just the part you need.

  • Join and pair

    chain() joins streams. pairwise() gives each item with the next one.

  • Running results

    accumulate() gives running totals, or a running maximum with max.

  • Pick and group

    combinations(), product() and groupby() for choosing and grouping.

itertools everywhere

These tools turn up wherever data is paired, grouped or repeated.

  • Turn ordercycle(players) hands out whose turn it is, round and round.
  • Bank balancesaccumulate(payments) shows the balance after each payment.
  • Outfit pickerproduct(shirts, trousers) lists every pair you could wear.
  • Trip legspairwise(stops) gives each leg of a journey: this stop to the next.

Taking a few from for ever

This line takes three numbers from an endless count. Tap each part to see its job.

Part 1 of 7

Tap any part of the code below, or press Next.1 of 7 explored

result:A real list: [10, 15, 20].

Loops in one line

Pick an example, change it, then press Run. Say what you expect to see before you press.

Example 1 of 6Endless, safely

Endless tools are safe as long as you only take what you need.

Your turn: Make count go up in tens. Then share the turns between four players.

Python
from itertools import count, cycle, islice

print(list(islice(count(1), 5)))
turns = cycle(["Ana", "Ben", "Cai"])
for _ in range(5):
    print("turn:", next(turns))
Output
Press Run to see what it prints.

Watch steps become totals

Press Step to run one line at a time. Watch the names box change.

Ready. Press Step to run the first line.

  1. from itertools import accumulate, pairwise
  2. walks = [2000, 3500, 1500]
  3. totals = list(accumulate(walks))
  4. gaps = [b - a for a, b in pairwise(totals)]
  5. print(totals)
  6. print(gaps)

Output so far

Nothing printed yet.

What Python does

Python reads the program from the top. Nothing has run yet.

Names

None yet.

Quick guesses

Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.

Question 1 of 6

1.repeat with a limit:

from itertools import repeat
print(list(repeat("hi", 3)))

0 of 6 answered

Common itertools misconceptions

Each card is something learners often believe. Tap it to see what Python really does.

Misconception 1 of 4

Notes

Everything above, in words. Open it when you want the full explanation.

Read the notesOpen

One import, many tools

Everything here lives in one module, usually imported whole or by name:

Try it 1: edit me, then Run
import itertools
from itertools import islice, chain, groupby
Output
Press Run to see what it prints.

Almost every itertools function returns a lazy iterator, so all the rules from the generator lessons apply: nothing is computed until you consume it, and each result can be consumed only once. Wrap a result in list() to see it or to keep it.

Endless iterators and islice

Three tools never stop on their own:

Try it 2: edit me, then Run
from itertools import count, cycle, repeat, islice

print(list(islice(count(100, 10), 4)))     # [100, 110, 120, 130]
print(list(islice(cycle("AB"), 5)))        # ['A', 'B', 'A', 'B', 'A']
print(list(repeat("-", 3)))                 # ['-', '-', '-']
Output
Press Run to see what it prints.

count(start, step) counts for ever; cycle(items) repeats a sequence for ever; repeat(x) gives the same value for ever, or n times if you pass a count. To take a slice of any iterator use islice(it, stop) or islice(it, start, stop). It works like list slicing, but on iterators, which have no [ ].

Endless iterators shine when paired with something finite. zip stops at its shortest input, so zip(count(1), names) numbers the names, and zip(names, cycle(["red", "blue"])) alternates two teams.

Joining and pairing streams

Try it 3: edit me, then Run
from itertools import chain, pairwise, zip_longest, batched

print(list(chain([1, 2], (3, 4), "ab")))               # [1, 2, 3, 4, 'a', 'b']
print(list(chain.from_iterable([[1, 2], [3]])))        # [1, 2, 3]
print(list(pairwise([10, 13, 19])))                     # [(10, 13), (13, 19)]
print(list(zip_longest("abc", [1], fillvalue=0)))       # [('a', 1), ('b', 0), ('c', 0)]
print(list(batched(range(7), 3)))                       # [(0, 1, 2), (3, 4, 5), (6,)]
Output
Press Run to see what it prints.
  • chain reads several iterables one after another, without building a combined list.
  • chain.from_iterable does the same for an iterable of iterables, which is a quick way to flatten one level.
  • pairwise gives each item with the next one: perfect for differences between readings.
  • zip_longest is zip that carries on to the longest input, filling gaps.
  • batched cuts a stream into tuples of a fixed size, the last one possibly shorter (added in Python 3.12).

Running results: accumulate

accumulate gives running totals, or running results of any two-argument function:

Try it 4: edit me, then Run
from itertools import accumulate
import operator

print(list(accumulate([5, 3, 2])))                 # [5, 8, 10]
print(list(accumulate([3, 1, 4, 1], max)))         # [3, 3, 4, 4]
print(list(accumulate([1, 2, 3, 4], operator.mul)))  # [1, 2, 6, 24]
Output
Press Run to see what it prints.

A bank balance after each transaction, the highest score so far and compound growth are all one accumulate call.

Grouping with groupby

groupby(items, key) walks through the items and starts a new group every time the key changes. It yields pairs of the key and an iterator over that group's items:

Try it 5: edit me, then Run
from itertools import groupby

words = ["apple", "avocado", "banana", "blueberry", "cherry"]
for letter, group in groupby(words, key=lambda w: w[0]):
    print(letter, list(group))
# a ['apple', 'avocado']
# b ['banana', 'blueberry']
# c ['cherry']
Output
Press Run to see what it prints.

The important word is consecutive. groupby does not look ahead or collect matching items from elsewhere: in ["a1", "b1", "a2"] the two a items end up in separate groups. To group by a key across the whole collection, sort by the same key first: groupby(sorted(items, key=k), key=k).

Each group is itself an iterator that shares the underlying stream with groupby. Use it (for example with list(group)) before moving on to the next key, because once groupby advances, the previous group is gone.

For counting rather than listing, collections.Counter is often simpler. groupby is the right tool when the data is already in order, such as log lines by date or rows sorted by customer.

Combinatorics

Three functions generate arrangements:

Try it 6: edit me, then Run
from itertools import combinations, permutations, product

team = ["ana", "ben", "cai"]
print(list(combinations(team, 2)))
# [('ana', 'ben'), ('ana', 'cai'), ('ben', 'cai')]
print(len(list(permutations(team, 2))))    # 6: order matters
print(list(product("ab", [1, 2])))
# [('a', 1), ('a', 2), ('b', 1), ('b', 2)]
Output
Press Run to see what it prints.
  • combinations(items, r): every group of r items where order does not matter, such as pairs of people for a meeting.
  • permutations(items, r): every ordered arrangement, such as first and second place.
  • product(a, b, ...): every way to pick one item from each input, which replaces nested for loops. product(range(3), repeat=2) is all pairs from one input.

These grow very fast. Ten items have 45 pairs, but 3,628,800 permutations. Because the results are lazy you can still loop over a huge number of them and stop early, but calling list() on one can exhaust memory.

Filtering helpers

takewhile(test, items) yields items while the test is true and stops at the first failure; dropwhile(test, items) skips items while the test is true and then yields everything after. They suit sorted or time-ordered data: "readings until the first error", "lines after the header".

Reading itertools code

When you see a loop with a counter, a flag or an index that peeks at the next item, ask whether an itertools function already expresses it. The resulting code is usually one line, but keep it readable: a chain of five nested itertools calls can be harder to follow than a plain loop. Name the intermediate iterators, as in the pipelines of the previous lessons, when a line gets long.

Syntax

The general shape of the statements in this lesson.

syntax.py
from itertools import (count, cycle, repeat, islice, chain, pairwise,
    zip_longest, batched, accumulate, groupby, combinations,
    permutations, product, takewhile, dropwhile)

islice(count(1), 5)              # 1 2 3 4 5
cycle("AB")                      # A B A B ... for ever
chain(a, b)                      # a's items, then b's
chain.from_iterable(lists)       # flatten one level
pairwise(xs)                     # (x0, x1), (x1, x2), ...
batched(xs, 3)                   # tuples of 3 (3.12+)
accumulate(xs)                   # running totals
groupby(sorted(xs, key=k), key=k)   # (key, group iterator)
combinations(xs, 2)              # unordered pairs
permutations(xs, 2)              # ordered pairs
product(a, b)                    # nested-loop pairs
takewhile(test, xs)              # until the first failure
Output
Press Run to see what it prints.

Worked examples

Read the problem, run the code, then read why it works.

Example 1 of 2

A weekly washing-up rota

Beginner

Four flatmates take turns washing up, one per day, starting on Monday. Print the first ten days of the rota with day numbers, and show who has washed up most often in those ten days.

Python
from itertools import count, cycle, islice
from collections import Counter

flatmates = ["Ana", "Ben", "Cai", "Dee"]
days = cycle(["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"])
turns = cycle(flatmates)

rota = list(islice(zip(count(1), days, turns), 10))
for number, day, person in rota:
    print(f"day {number:>2} {day}: {person}")

counts = Counter(person for _, _, person in rota)
print("Most turns:", counts.most_common(2))
Output
Press Run to see what it prints.

Predict first

How it works(open after your guess)

count, and both cycle calls are endless, but zip pulls one item from each at a time and islice stops after ten, so the program finishes. Because the week has seven days and there are four people, the pattern of who washes up on Monday changes every week. The rota is stored in a list because it is used twice.

Common pitfalls

Mistakes people make with this topic, and what to write instead.

Pitfall 1 of 3

groupby on unsorted data

Spot the bug

Can you see what is wrong? Run it to watch it go wrong, then open the fix.

Buggy code: run it
from itertools import groupby
items = ['apple', 'banana', 'avocado']
for letter, group in groupby(items, key=lambda w: w[0]):
    print(letter, list(group))
Output
Press Run to see what it prints.
Show what goes wrong and the fix

What happens

Prints a group for a twice: a ['apple'], b ['banana'], a ['avocado']

Write this instead

from itertools import groupby
items = sorted(['apple', 'banana', 'avocado'], key=lambda w: w[0])
for letter, group in groupby(items, key=lambda w: w[0]):
    print(letter, list(group))

Why it happens

groupby only joins consecutive items with the same key; it never looks further ahead.

In the real world

Where this shows up in software people use every day.

  1. Building a browser test matrix

    Quality assurance

    Before each release, a web team runs its checkout tests on every combination of browser, screen size and language. Some combinations are known to be unsupported. Writing the list by hand is error-prone, so they generate it, skip the exclusions, and split the rest into batches for their three test machines.

    Why Python fits

    product replaces three nested loops and produces all 12 combinations in a predictable order; one is filtered out. batched cuts the 11 remaining runs into groups of four for the machines, and count(1) numbers them. Adding a fourth browser is a one-word change.

    Python
    from itertools import product, batched, count
    
    browsers = ["chrome", "firefox", "safari"]
    screens = ["phone", "desktop"]
    languages = ["en", "de"]
    unsupported = {("safari", "phone", "de")}
    
    runs = [combo for combo in product(browsers, screens, languages) if combo not in unsupported]
    print("Total runs:", len(runs))
    
    for machine, batch in zip(count(1), batched(runs, 4)):
        print(f"machine {machine}:", ", ".join("/".join(combo) for combo in batch))
    Output
    Press Run to see what it prints.

Key takeaways

Tick each one you could explain to a friend.

0 of 5

Common questions

Guess the answer first, then open it.

Why use islice instead of slicing a list?

Iterators such as generators, files and itertools results do not support [2:5]. islice slices any iterator lazily, without converting it to a list first.

What is the difference between combinations and permutations?

Combinations ignore order: (ana, ben) and (ben, ana) are the same pair, counted once. Permutations treat them as different, so there are more of them.

Is batched available everywhere?

It was added in Python 3.12. On older versions, a short generator that collects items into a list and yields it when full does the same job, as in the generators lesson.

Are itertools functions faster than writing loops?

They are written in C and are usually at least as fast as an equivalent Python loop. The bigger win is clarity: a well-named tool says what the loop is for.

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

Where to go next

The quiz and the Lab live on their own pages, so this lesson stays about learning.

Finished this lesson?

Create an ID or sign in to save your progress across devices.

Create ID to save
Lessons done in this module0/4 complete
Quiz

Check what you learned

12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.

Lab

Keep going in the Lab

7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.

Review

Spaced review

Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.

This lesson at a glance

The 15 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.

What else you can search for and explore

Curious to go further? Each card opens a web search in a new tab.

References

Look things up here whenever you need the exact details.