Mental Model
Think of
This is why it feels familiar: it relies on lazy evaluation, just like the generators and
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)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)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
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.