Lompati ke konten utama
eLearner.app
Modul 6 · Pelajaran 4 dari 424/36 dalam kursus~12 min
Pelajaran modul (4/4)

Itertool penting

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

Latihan#python.m6.l4.e1
Upaya: 0Memuat…

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

Memuat editor…
Tunjukkan petunjuk

dict(zip(countries, capitals))

Solusi tersedia setelah 3 upaya

Review exercise

Latihan#python.m6.l4.e2
Upaya: 0Memuat…

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

Memuat editor…
Tunjukkan petunjuk

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

Solusi tersedia setelah 3 upaya

Additional challenge

Latihan#python.m6.l4.e3
Upaya: 0Memuat…

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.

Memuat editor…
Tunjukkan petunjuk

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

Solusi tersedia setelah 3 upaya