Legends ofPythos
Claim your name
Pythonic Python

Useful tools in itertools

Lesson 4 of 12

Watch the lesson0:59 ยท 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.
You will see this in real programs when processing log files or sensor data. If a file has one million lines, loading them all into memory crashes your program. With itertools, you process line-by-line on the belt without ever holding the whole thing at once.

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 never enter an infinite loop because you only ask for what you need.
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.
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.
Write your Python here.

Run your code to check it against the tests.