This tutorial was built using Python 3.6
In this tutorial we’ll be looking at what
iterators are with Python. We’ll also be looking at how we can effectively work with them and improve our Python programs using them.
What Are Iterators?
Iterators are cool in the sense that they allow us to step over every item in an array, object or file and perform work on each item. For example, we could take the string
test and use an iterator to step over every character element within that string.
Iterables in Python represent something that we can actively iterate over. These are things like
sets and even
strings as we’ve seen in the previous demonstration. If we wish to turn an
iterable into an
iterator then we can use the
iter built in function which takes in the
iterable like so:
When we have an
iterator object we can effectively step through it using the
next() method. This will simply return the next element of the given
iterator object, if no further elements exist in the
iterator then a
StopIteration exception will be raised: