Iterators and iterables

Iterators and iterables

This section focuses on iterators, generators, and comprehensions, which are essential for writing efficient and Pythonic code. You'll learn how to handle data streams and create concise loops to enhance your programming capabilities.

5 audio · 1:16

Nortren·

What is the difference between an iterable and an iterator?

0:16
An iterable is any object that can return an iterator, by implementing dunder iter. An iterator is an object that produces values one at a time, by implementing both dunder iter and dunder next. Lists and dicts are iterables but not iterators. Calling iter on an iterable returns an iterator.

How does the for loop work internally?

0:15
A for loop calls iter on the iterable to get an iterator, then repeatedly calls next on the iterator. Each call returns the next value, which is bound to the loop variable. When the iterator is exhausted, it raises StopIteration, and the loop exits cleanly without propagating the exception.

What is StopIteration?

0:15
StopIteration is the exception raised by an iterator's next method to signal that there are no more values. The for loop catches it automatically. Manually iterating with next can let you handle StopIteration explicitly. Inside generators, returning from the function raises StopIteration implicitly.

How do you make a class iterable?

0:14
Implement dunder iter on the class. The method should return an iterator, which can be the object itself if it also implements dunder next, or a separate iterator object. For most cases, returning a generator from dunder iter is the cleanest approach.

What does the iter function do?

0:16
The iter function returns an iterator from an iterable. It calls the iterable's dunder iter method. There is also a two-argument form: iter of a callable and a sentinel returns an iterator that calls the callable until it returns the sentinel. This is useful for iterating over file reads or network responses. ---