Python·100 questions

What is an iterator and an iterable?

Answer

In the Python ecosystem, the concepts of an iterable and an iterator are closely related but perform different roles in the process of traversing collections. An iterable is any data structure whose elements can be traversed in a for loop, such as lists, strings, dictionaries, or files. Such an object knows how to provide access to its elements, but does not store the state of the current step on its own.

An iterator, in turn, is a standalone stateful object that remembers its current position and knows how to get the next element.

To clearly understand the difference and mechanics of these entities, let's look step-by-step at how the iteration process works under the hood:

You pass the iterable to the built-in iter(obj) function, which calls its internal __iter__ method and returns a full-fledged iterator.
The for loop or another consumer starts calling the next(it) function on the obtained iterator.
The iterator returns the next element of the sequence, shifting the internal pointer forward each time.
When the elements run out, the iterator raises a special StopIteration exception, which signals the loop to terminate.

It is worth noting that all function and expression generators are also iterators, as they lazily compute values on the fly and consume a minimal amount of RAM.

Was this answer helpful?

More questions in this topic

Related questions from other topics