What is an iterator and an iterable?
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:
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.