#Python Iterator Tutorial
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.
>>> string = "test"
>>> for character in string:
>>> print(character)
## Output
t
e
s
t
Iterables
Iterables in Python represent something that we can actively iterate over.
These are things like lists, 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:
>>> string = "test"
>>> iterator = iter(string)
>>> iterator = iter(string)
>>> print(iterator.next())
t
>>> print(iterator.next())
e
>>> print(iterator.next())
s
>>> print(iterator.next())
t
The next() Method
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:
>>> iterator = iter(string)
>>> print(iterator.next())
t
>>> print(iterator.next())
e
>>> print(iterator.next())
s
>>> print(iterator.next())
t
>>> print(iterator.next())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
Under Construction
Continue Learning
Working with Lists in Python - Tutorial
In this tutorial we will look at how we can work with lists in Python
Working With The File System in Python
In this tutorial we evaluate the different ways you can work with the file system in Python
Getting Started With Python
An absolute beginners introduction to the Python programming language
Functions and Variables in Python
In this tutorial we introduce the concept of both functions and variables and how we can use them in our Python programs