Legends ofPythos
Claim your name
Pythonic Python

Useful tools in itertools

Lesson 4 of 12

Watch the lesson5:27 ยท with Sigrid

Mental Model

Think of itertools as a conveyor belt. Instead of dumping all boxes into one giant warehouse (a list), you keep them moving on the belt. You take what you need, and the rest waits for the next worker.

This is why it feels familiar: it relies on lazy evaluation, just like the generators and yield statements you already use. Many of its tools take any iterable: anything a for loop can go through, such as a list, a piece of text, a range or a generator.
You will see this in real programs when processing log files or sensor data. If a file has a million lines, loading them all at once can use a lot of memory. With itertools, you handle one line at a time on the belt, without ever holding the whole file.

Chaining Iterables

from itertools import chain

class_a = ['alice', 'bob']
class_b = ['carol', 'dave']
roster = list(chain(class_a, class_b))
print(roster)
Combining two lists with chain
chain connects the end of one iterable to the start of another. It yields items from class_a, then switches seamlessly to class_b. The example above creates a single flat roster without writing any manual loops.

Endless Sequences

from itertools import count, islice

ticket_numbers = count(start=100)
next_three = list(islice(ticket_numbers, 3))
print(next_three)
Slicing an infinite stream with count and islice
count generates numbers forever. islice acts like a gate: it lets exactly three items through and then stops asking for more.
The example above produces [100, 101, 102]. You don't get stuck in an endless loop, because you only ask for what you need.

count can also take a step: how much to add each time. count(start=0, step=2) counts 0, 2, 4, 6 and so on.
These tools give you control over how data flows. You choose when items appear and how many to keep in memory.

Now try combining two lists with chain for your first exercise, then use count and islice to generate the specific numbers requested in the second task.

Your turn

0 of 2 solved

Exercise 1

+35 XP
Use chain to combine the two lists into one flat list called result, then print it. Start with from itertools import chain, above the two lists.
list_a = [1, 2]
list_b = ['a', 'b']

Run your code to check it against the tests.

Exercise 2

+35 XP
Use count and islice to get the first five multiples of three, starting from zero. Store them in a list called result and print it. Start with from itertools import count, islice. count also takes a step: count(start=100, step=10) counts 100, 110, 120, and so on.
Write your Python here.

Run your code to check it against the tests.