liveBook · Manning

Iterator method

As explained in Python How-To

iter is a Python built-in function that returns an iterator for an iterable object or raises an exception when the object is not iterable.

Need to retrieve items one at a time? Call iter() on an iterable to create an iterator. The iterator supplies elements through next(), and calling next() after exhaustion raises StopIteration. Calling iter() on a non-iterable raises TypeError. section 5.1.1 section 5.1.2

Use iter() in these practical ways:

  • Create an iterator explicitly: tasks_iterator = iter(tasks). section 5.1.1
  • Retrieve successive elements with next(tasks_iterator) until the iterator is exhausted. section 5.1.1
  • Test iterability by calling iter(obj) and handling TypeError when conversion fails. section 5.1.2
  • Prefer a for loop for ordinary iteration; Python creates and advances the iterator and handles exhaustion safely. section 5.1.1

Read a list through its iterator

tasks = ["task0", "task1", "task2"] tasks_iterator = iter(tasks) print(next(tasks_iterator)) # task0 print(next(tasks_iterator)) # task1 print(next(tasks_iterator)) # task2 # A further next(tasks_iterator) raises StopIteration section 5.1.1

Figure 5.1 The workflow of iteration with iterators. Iterators are created by using the iter function from iterables. The iterators use the next function to retrieve the next item, if available. When the iterator exhausts its items, the StopIteration exception is raised.
CH05_F01_Cui

Follow the iteration workflow from iterable to iterator, then from iterator to successive next() calls and StopIteration. section 5.1.1

How Python How-To covers it

How deep it goes
Traces iterator creation, successive next() calls, exhaustion, and automatic handling inside for loops.
Examples
Demonstrates iter() with lists, integers, and common built-in iterable types including strings, tuples, dictionaries, sets, ranges, maps, and filters.
What you can do after
Apply iter() and next() to inspect iterability and retrieve iterable elements one at a time.
How it connects
Connects iter() with iterables, iterators, next(), StopIteration, and for loops.

Also explained in

Compare how 2 books explain iterator method →

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.