Skip to main content
eLearner.app
Module 6 · Lesson 4 of 424/36 in the course~12 min
Module lessons (4/4)

Essential itertools

Python exposes plenty of iteration tools: some are built-in (always available), others live in the itertools module of the standard library. Here are the most important ones.

enumerate: index + value

When you need both the index and the element during a loop:

Python
for i, parola in enumerate(["a", "b", "c"]):
    print(i, parola)
# 0 a
# 1 b
# 2 c

# parte da un altro numero:
for i, parola in enumerate(["a", "b", "c"], start=1):
    print(i, parola)

zip: iterate in parallel

Combines multiple iterables element by element:

Python
nomi = ["Ada", "Linus", "Grace"]
eta = [36, 54, 85]

for n, e in zip(nomi, eta):
    print(f"{n} ha {e} anni")

zip stops at the shortest iterable. For a "long" zip use itertools.zip_longest.

Building a dict from two parallel lists:

Python
dict(zip(nomi, eta))
# {'Ada': 36, 'Linus': 54, 'Grace': 85}

itertools.chain: concatenate iterables

Python
from itertools import chain
list(chain([1, 2], [3, 4], [5]))
# [1, 2, 3, 4, 5]

Without creating an intermediate list: useful for files, generators, etc.

itertools.count and repeat: infinite iterators

Python
from itertools import count, repeat

# count(start, step) — interi crescenti infiniti
for i in count(10, 2):
    if i > 20: break
    print(i)
# 10, 12, 14, 16, 18, 20

# repeat(x, n) — ripete lo stesso valore n volte (o all'infinito senza n)
list(repeat("ok", 3))   # ['ok', 'ok', 'ok']

itertools.combinations

All combinations (without repetitions, order-independent) of a given length:

Python
from itertools import combinations
list(combinations([1, 2, 3, 4], 2))
# [(1,2), (1,3), (1,4), (2,3), (2,4), (3,4)]

Ordered variant: permutations. Variants with repetition: combinations_with_replacement and product.

zip() for dictionaries and unbalanced iterables

The zip() function stops as soon as the shortest input iterable is exhausted. If you want to pair elements and keep any excess values (filling them with a default value like None), you can use zip_longest() from the itertools module. Additionally, you can pass a zip result directly to dict() to instantly build a key-value map.

Try it

Exercise#python.m6.l4.e1
Attempts: 0Loading…

Given the parallel lists `countries = ['Italia', 'Francia', 'Spagna']` and `capitals = ['Roma', 'Parigi', 'Madrid']`, build `mapping` as a dict {country: capital}. Evaluate `mapping`.

Loading editor…
Show hint

dict(zip(countries, capitals))

Solution available after 3 attempts

Review exercise

Exercise#python.m6.l4.e2
Attempts: 0Loading…

Given `words = ['ciao', 'mondo', 'python']`, build `enumerated_items` as a list of tuples (i, word) starting from i=1. Evaluate `enumerated_items`.

Loading editor…
Show hint

enumerate(words, start=1) → (i, value) tuples.

Solution available after 3 attempts

Additional challenge

Exercise#python.m6.l4.e3
Attempts: 0Loading…

Given two lists `keys = ['a', 'b', 'c']` and `values = [10, 20, 30]`, use `zip` to pair them and convert the result into a dictionary. Store the resulting dictionary in `my_dict` and evaluate it.

Loading editor…
Show hint

Use dict(zip(keys, values)) and assign it to my_dict.

Solution available after 3 attempts