liveBook · Manning

Iterator

As explained in Python How-To

An iterator is an object that produces successive items through Python's iteration protocol.

How can you process a list one item at a time? An iterator supplies successive items. Call iter on an iterable to obtain an iterator, then call next to retrieve each item. Once there are no items left, next raises StopIteration. section 5.1.1

Retrieve items one by one

tasks = ["task0", "task1", "task2"] tasks_iterator = iter(tasks) next(tasks_iterator) # 'task0' next(tasks_iterator) # 'task1' next(tasks_iterator) # 'task2' next(tasks_iterator) # raises StopIteration Each call advances through the available items. Usually, a for loop is simpler: `for task in tasks: print(task)` prints the three tasks and exits normally when the iterator is exhausted. section 5.1.1

You rarely need to create an iterator explicitly. A for loop handles iterator creation and StopIteration for you. Functions can also return iterators that fit directly into a loop. section 5.1.1 section 5.3.2

Choose the iterator-producing function that matches the task:

  • `reversed(tasks)` supplies list items in reverse order without calculating indexes. section 5.3.2
  • `zip(tasks, dates, locations)` supplies tuples of aligned items; unpack each tuple in the loop. By default, zip stops when the shortest iterable is exhausted. section 5.3.3
  • `list(map(float, numbers_str))` collects the converted values produced by a map iterator. section 5.1.3

Consume a CSV header separately

For a CSV file whose first row contains field names: with open("tasks.txt", newline="") as file: csv_reader = csv.reader(file) fields = next(csv_reader) for row in csv_reader: print(dict(zip(fields, row))) After next consumes the header, the loop begins with the second row. A file with columns `task_id,title,urgency` can produce `{'task_id': '1001', 'title': 'Homework', 'urgency': '5'}`. If the goal is simply to read header-based rows as dictionaries, `csv.DictReader(file)` is cleaner. section 11.2.2

How Python How-To covers it

How deep it goes
Walks through iter, next, exhaustion, and StopIteration, then demonstrates automatic for-loop handling; stops short of implementing a custom iterator.
Examples
Traces a three-item list iterator and consumes a CSV header before processing the remaining rows.
What it assumes
Assumes familiarity with lists and for loops while explaining how iter and next drive iteration.
What you can do after
Apply it via Python's iter, next, and csv.reader to consume elements or rows one at a time.
How it connects
Connects iterables, for loops, StopIteration, zip, and tuple unpacking.

Also explained in

Compare how 15 books explain iterator →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.