Module lessons (1/4)
for loops and range
The for loop in Python is used to iterate over a sequence of items:
a list, a string, a range, a dict… anything that is "iterable".
parole = ["ciao", "mondo", "!"]
for p in parole:
print(p)
# ciao
# mondo
# !The pattern is always the same: for <variable> in <iterable>: followed by
the indented block that will be executed once for each item.
range(...): generating integer intervals
range produces a lazy sequence of integers. Three forms:
range(5) # 0, 1, 2, 3, 4
range(2, 6) # 2, 3, 4, 5
range(0, 10, 2) # 0, 2, 4, 6, 8 (step)
range(5, 0, -1) # 5, 4, 3, 2, 1 (negative step)range is exclusive on the right end, like slice. It is a lazy object:
it does not allocate memory for all the numbers, it produces them one at a time.
totale = 0
for i in range(1, 11):
totale = totale + i
totale # 55 (1+2+...+10)Iterating with an index: enumerate
When you need the item and its index together, use enumerate:
parole = ["ciao", "mondo", "!"]
for i, p in enumerate(parole):
print(i, p)
# 0 ciao
# 1 mondo
# 2 !enumerate produces (index, value) pairs that we assign directly to two
variables via tuple unpacking (we'll see it in the module dedicated to
data structures).
Iterating two sequences in parallel: zip
nomi = ["Ada", "Linus", "Grace"]
anni = [36, 54, 79]
for n, a in zip(nomi, anni):
print(f"{n} ha {a} anni")zip stops at the shortest sequence.
range() and Python's laziness
In Python, the range() function does not allocate an actual list in memory: it returns a lazy generator that yields numbers one at a time as requested (for example, in a for loop). This allows iterating over millions of integers without bloating RAM. To inspect range values as a list, you can cast it explicitly with list(range(5)).
Try it yourself
Compute the sum of the numbers from 1 to 100 (inclusive) using a for loop over range(...), assign it to `total` and evaluate it.
Show hint
range(1, 101) generates 1, 2, ..., 100 (exclusive on the right).
Solution available after 3 attempts
Review exercise
Given the list `words = ['uno', 'due', 'tre']`, build a list `pairs` of strings like '0:uno', '1:due', '2:tre' using enumerate. Evaluate `pairs`.
Show hint
enumerate(words) returns (index, value) at each iteration.
Solution available after 3 attempts
Additional challenge
Calculate the sum of all even numbers from 2 to 20 inclusive using a `for` loop over a `range`. Store the final sum in `even_sum` and evaluate it.
Show hint
Use range(2, 21, 2) to iterate only over even integers from 2 to 20.
Solution available after 3 attempts