Iterables in Python
Understand the concept of iterables and how Python uses the iter function to create iterators. Learn how the next function retrieves items until the StopIteration exception signals completion. This lesson clarifies iteration mechanics behind Python's for loops and other iteration contexts.
We'll cover the following...
What is iterable?
Any object from which the iter built-in function can acquire an iterator is called iterable.
All sequences are iterable.
💡 Python obtains iterators from iterables.
Mostly, we iterate via a for loop. For example:
It will give the following output.
H
e
l
l
o
Have you ever wondered about how appealingly loops function in Python? With such a self-explanatory syntax, the loop iterates over a sequence. But what if we had no for loops?
Iterating using the iter function
The absence of the for loop will make us write a little drawn-out code. Run the following example.
Seemingly, message is an iterable (as it’s a string). At line 2, we are creating an iterator it from an iterable message using the iter() function. The next item is obtained repeatedly using the next function (at line 6). To halt the iteration, we raise the StopIteration exception where there’s nothing left to read from message.
The figure below can help you visualize this concept.
StopIteration exception
StopIteration signals that the iterator is exhausted. This exception is handled internally in for loops and other iteration contexts like list comprehensions, tuple unpacking, etc.
The discussion on the iter function speaks to Python’s beauty that you can read a Pythonic loop as if it was an English sentence.