Python · Module 2 · Lesson 21 min read

for Loops

Looping over anything iterable

A for loop takes each item from a sequence (list, string, tuple, dict, range…) one at a time.

range()

  • range(5) → 0, 1, 2, 3, 4 (stop is not included)
  • range(1, 6) → 1 to 5
  • range(10, 0, -2) → 10, 8, 6, 4, 2

range is lazy: it creates numbers as needed instead of storing them all.

enumerate(): index and value together

Python
for i, fruit in enumerate(fruits, start=1):

Avoid for i in range(len(fruits)), which is harder to read.

zip(): loop over two lists at once

for name, score in zip(names, scores):

Looping over a dictionary

for key, value in scores.items():

⚠️ Don't add or remove items from a list while looping over it. Loop over a copy (for x in items[:]) or build a new list.

▶️ Runs in the app.

Example

Python
for i in range(1, 6):
    print(i, end=" ")
print()                               # 1 2 3 4 5

fruits = ["apple", "banana", "mango"]
for i, fruit in enumerate(fruits, start=1):
    print(i, fruit)                   # 1 apple / 2 banana / 3 mango

names = ["Ana", "Ben"]
scores = [91, 78]
for name, score in zip(names, scores):
    print(f"{name}: {score}")

total = 0
for n in range(1, 101):
    total += n
print("Sum 1..100 =", total)          # 5050