liveBook · Manning

Next

As explained in Python How-To

An iterator operation that advances an iterator and returns its next value or result, with behavior on exhaustion determined by the API.

Call `next(iterator)` to retrieve the next available item. When the iterator is exhausted, `next` raises `StopIteration`. For ordinary iteration, a `for` loop handles exhaustion automatically. section 5.1.1

next(tasks_iterator)
# output: 'task0'
 
next(tasks_iterator)
# output: 'task1'
 
next(tasks_iterator)
# output: 'task2'
 
next(tasks_iterator)
# ERROR: StopIteration

Repeated calls retrieve the task items in order; another call after the last item raises `StopIteration`. section 5.1.1

A practical use is consuming a CSV header with `next(csv_reader)`. The subsequent loop then processes the remaining rows. For header-based dictionaries, `csv.DictReader` provides a cleaner alternative. section 11.2.2

How Python How-To covers it

How deep it goes
Explains iterator advancement and `StopIteration` on exhaustion, then contrasts manual calls with exhaustion handling in `for` loops.
Examples
Demonstrates retrieving task-list items and consuming a CSV header before iterating over its data rows.
What it assumes
Explains that `iter()` converts an iterable to an iterator before `next` retrieves its items.
What you can do after
Apply it by retrieving iterator items manually or consuming a CSV header before looping over remaining rows.
How it connects
Connects iterators with iterables, `iter()`, `StopIteration`, `for` loops, and `csv.reader`.

Also explained in

Compare how 5 books explain next →

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.