Python Intermediate - Lesson 19 - Iterators and Generators

Python Intermediate · Lesson 19

Iterators and Generators

Python can produce values one at a time instead of building a large list first. Iterators and generators are useful for processing files, records, or calculated sequences in a steady stream.

By the end, you can: use iter() and next(), write a generator function with yield, create a generator expression, and process a stream of CSV rows without loading the whole file into memory.
One-pass reminder: a generator is usually consumed as you loop over it. If you need to process the same values multiple times, create a new generator or deliberately save the values in a collection.

1. Iterable versus iterator

An iterable can provide an iterator. Lists, strings, and dictionaries are common iterables. An iterator produces the next value when asked and remembers where it is in the sequence.

topics = ["functions", "files", "testing"]
topic_iterator = iter(topics)

print(next(topic_iterator))
print(next(topic_iterator))
print(next(topic_iterator))

Calling next() again after all values are used raises StopIteration. A for loop handles that stopping signal for you.

2. Write a generator function with yield

A generator function uses yield to produce one value and pause. It resumes from that point when the next value is requested.

def count_up_to(limit):
    number = 1
    while number <= limit:
        yield number
        number += 1


for value in count_up_to(4):
    print(value)

Calling count_up_to(4) creates a generator; it does not immediately build a list of every result. The loop requests each next value in turn.

3. Use a generator expression

A generator expression looks like a list comprehension with parentheses. It calculates each result as the program asks for it.

squares = (number * number for number in range(1, 6))

for square in squares:
    print(square)

Compare it with [number * number for number in range(1, 6)], which builds a list immediately. The generator expression is useful when you only need to consume values once.

4. Stream lines from a file

A file object is iterable. Looping over it reads lines as you go, which can be more memory-efficient than calling read_text() for a very large file.

from pathlib import Path

log_path = Path("app.log")

with log_path.open(encoding="utf-8") as log_file:
    for line in log_file:
        if "ERROR" in line:
            print(line.rstrip())

The file is opened only while the with block runs. If you write a generator that reads a file, keep the file context inside the generator function so it stays open during iteration and closes when the generator finishes.

5. Yield parsed records from a CSV

A generator can validate and transform rows as it reads them. Here, csv.DictReader supplies each row as a dictionary, and the generator yields only valid study sessions.

import csv
from pathlib import Path


def read_sessions(csv_path):
    with Path(csv_path).open(
        newline="",
        encoding="utf-8"
    ) as csv_file:
        reader = csv.DictReader(csv_file)
        for row_number, row in enumerate(reader, start=2):
            topic = (row.get("topic") or "").strip()
            raw_minutes = (row.get("minutes") or "").strip()
            try:
                minutes = int(raw_minutes)
            except ValueError:
                print(f"Skipping row {row_number}: invalid minutes")
                continue

            if not topic or minutes <= 0:
                print(f"Skipping row {row_number}: invalid session")
                continue
            yield topic, minutes

Hands-on exercises

  1. Write a generator function even_numbers(limit) that yields even numbers from 2 up to and including limit.
  2. Use a generator expression to produce the lengths of words longer than four characters in a list of words. Print each length.
Show Solution & Common Mistakes

Exercise 1 — one possible solution

def even_numbers(limit):
    number = 2
    while number <= limit:
        yield number
        number += 2


for even in even_numbers(10):
    print(even)

Exercise 2 — one possible solution

words = ["code", "generator", "loops", "iterator"]
lengths = (len(word) for word in words if len(word) > 4)

for length in lengths:
    print(length)

Common mistakes:

  • Using return where a generator needs yield. A normal return ends the function instead of producing a sequence.
  • Expecting a generator to print or calculate every value when it is created. It produces values as it is iterated.
  • Reusing an exhausted generator. Create it again or save values in a list if you need another pass.
  • Forgetting to close a file used by a generator. Put the file's with block inside the generator.
  • Trying to use len() on a generator. Count values while iterating, or materialize them if the collection is intentionally small.

Quick quiz

Choose an answer, then select Check answer.

1. What does yield do in a generator function?

2. When does a generator expression produce its values?

3. What should you do if you need to iterate over the same generated values again?

Mini-project: Stream a Study Sessions CSV

Build a report that reads a CSV file row by row, skips invalid records, and calculates the valid session count and total study minutes without loading all rows into a list.

Requirements:

  • Read a file named study_sessions.csv.
  • Expect the headers topic and minutes.
  • Yield each valid topic and positive whole-number duration.
  • Skip invalid rows with a clear message.
  • Calculate count and total by consuming the generator once.
  • Handle a missing CSV file with a helpful message.

Sample CSV:

topic,minutes
Functions,25
SQLite,35
Web APIs,20
Review,not-a-number
,15

Hint: use csv.DictReader and enumerate(reader, start=2) to include the header row when reporting the source line number.

Show Full Project Solution
import csv
from pathlib import Path


CSV_PATH = Path("study_sessions.csv")


def read_sessions(csv_path):
    """Yield valid (topic, minutes) pairs from a CSV file."""
    with Path(csv_path).open(
        newline="",
        encoding="utf-8"
    ) as csv_file:
        reader = csv.DictReader(csv_file)
        required_columns = {"topic", "minutes"}
        if not required_columns.issubset(reader.fieldnames or []):
            raise ValueError("CSV must have topic and minutes columns.")

        for row_number, row in enumerate(reader, start=2):
            topic = (row.get("topic") or "").strip()
            raw_minutes = (row.get("minutes") or "").strip()

            try:
                minutes = int(raw_minutes)
            except ValueError:
                print(f"Skipping row {row_number}: minutes is not a whole number.")
                continue

            if not topic:
                print(f"Skipping row {row_number}: topic is blank.")
                continue
            if minutes <= 0:
                print(f"Skipping row {row_number}: minutes must be positive.")
                continue

            yield topic, minutes


def summarize_sessions(sessions):
    """Consume an iterable once and return its count and minute total."""
    count = 0
    total_minutes = 0

    for topic, minutes in sessions:
        print(f"{topic}: {minutes} minutes")
        count += 1
        total_minutes += minutes

    return count, total_minutes


def main():
    try:
        sessions = read_sessions(CSV_PATH)
        count, total = summarize_sessions(sessions)
    except FileNotFoundError:
        print(f"Create {CSV_PATH} first using the sample CSV from the lesson.")
        return
    except (OSError, ValueError) as error:
        print(f"Could not read the session file: {error}")
        return

    print(f"Valid sessions: {count}")
    print(f"Total study time: {total} minutes")


if __name__ == "__main__":
    main()

Save the sample CSV in the same folder as the script, then run the script. The generator reads and validates each row as the summary loop requests it. It does not build a list of every record.

The generator is consumed by summarize_sessions(). If you need another report, call read_sessions(CSV_PATH) again to create a fresh generator.

Posts les plus consultés de ce blog

Python Programming Exercises with Solutions - Complete Beginner's Guide

Python Basics - Capstone - Study Sprint Tracker

Python Intermediate - Lesson 10 - Working with Excel Spreadsheets