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.
Follow the iteration workflow from iterable to iterator, then from iterator to successive next() calls and StopIteration. section 5.1.1

