indusai.co

For loops

A for loop runs a block once for each item in a sequence. It is the loop you will write most often in Python, and it works with lists, strings, dictionaries, files and anything else that can be iterated.

Looping over a list

python
languages = ["Python", "Go", "Rust"]
for lang in languages:
    print(lang)

lang takes each value in turn. You choose the name; make it describe one item.

Looping over a string

python
for ch in "abc":
    print(ch.upper())

range()

range produces a sequence of numbers without building a list in memory.

python
for i in range(5):          # 0 to 4
    print(i)

for i in range(2, 6):       # 2 to 5
    print(i)

for i in range(10, 0, -3):  # 10, 7, 4, 1
    print(i)

range(start, stop, step): start is included, stop is not.

enumerate()

When you need the index as well as the item, use enumerate rather than range(len(...)).

python
tasks = ["write", "test", "deploy"]
for i, task in enumerate(tasks, start=1):
    print(f"{i}. {task}")

zip()

zip loops over two or more sequences together.

python
names = ["Isha", "Kabir", "Leela"]
scores = [88, 92, 79]
for name, score in zip(names, scores):
    print(name, score)

It stops at the shortest sequence.

Looping over a dictionary

python
stock = {"pen": 40, "book": 12}
for item, qty in stock.items():
    print(item, qty)

break, continue and else

These work the same way as in while loops.

python
for n in range(2, 20):
    for d in range(2, n):
        if n % d == 0:
            break
    else:
        print(n, "is prime")

Nested loops

python
for row in range(1, 4):
    for col in range(1, 4):
        print(row * col, end="\t")
    print()

end="\t" tells print to put a tab instead of a newline after each value.

Do not modify a list while looping over it

Removing items from a list you are iterating skips elements. Loop over a copy or build a new list instead.

python
nums = [1, 2, 3, 4, 5, 6]
kept = [n for n in nums if n % 2 == 0]
print(kept)

reversed() and sorted()

python
for n in reversed([1, 2, 3]):
    print(n)

for w in sorted(["pear", "apple", "fig"]):
    print(w)

Practice

  1. Print the multiplication table of 7 from 1 to 10 using range.
  2. Given two lists, items = ["tea", "samosa"] and prices = [10, 15], print a receipt line for each and the total.
  3. Count the vowels in the sentence "machine learning is fun" with a for loop.