You might have always encountered the word iterable in many Python-related blogs. Ever wondered what it actually means, apart from the fact that it can be traversed through or iterated over? If not, this is the right place for you to know about iterators and iterables in-depth.
Iterators are a Python type that is used in for
loops or any other loop. Apart from being seen with for
loops, they are implemented in data structure comprehensions, generators, but are not explicitly addressed. Iterators are simple objects which can be traversed over, returning one data element at a time. Inbuilt iterators in Python include strings, lists, tuples, dictionaries, and sets, etc.
Why are the above-mentioned data structures iterators?
The strings, list, tuples, dictionaries, and sets, etc, come under iterators since they implement the __iter__
and __next__
methods in Python. The __iter__
and the __next__
methods are 2 special methods, and are together known as iterator protocol. What are these __iter__
and __next__
methods? They have been discussed right below.
1. The __iter__
method
This method is called the moment an iterator is initialized. When the iter()
method is called, under the hood it calls the __iter__
method which returns an iterator. It returns an object that has the ability to call the __next__
method, using which, one by one each data element stored in the iterable can be traversed.
2. The __next__
method
This method, in Python 2.x was known as next. But it was changed to __next__
in Python 3.x version. This method returns the next value stored in the iterator object, The for
loop implicitly calls the __next__
method when an iterator is used with it. When the end of the iteration is reached, this method raises a StopIteration error.
We will look at how they are implemented in inbuilt iterators.
1. Iterating over string
my_string = "Studytonight"
for i in my_string:
print(i)
Output:
S
t
u
d
y
t
o
n
i
g
h
t
2. Iterating over list
my_list = ["Study", "tonight", "12"]
for i in my_list:
print(i)
Output:
Study
tonight
12
3. Iterating over tuple
my_tuple = ("Studytonight", "is", "fun")
for i in my_tuple:
print(i)
Output:
Studytonight
is
fun
4. Iterating over dictionary
my_dict = dict()
my_dict['Study'] = 5
my_dict['tonight'] = 7
for i in my_dict :
print("%s : %d" %(i, my_dict[i]))
Output:
Study : 5
tonight : 7
5. Iterating over objects using the iter method explicitly
The iter
method creates an iterator with the help of which the object elements can be traversed upon. Once the last element has been displayed/used, it gives a StopIteration error indicating that there is nothing to display and the iteration had to be stopped.
my_list = [1, 7, 8, 3.45]
my_iter = iter(my_list) # Obtain an iterator using the iter()
print(next(my_iter)) # Iterate through it with the help of next() method
print(next(my_iter)) # Next method calls the __next__ method
print(my_iter.__next__())
print(my_iter.__next__())
next(my_iter) # Raises error since all the elements have been
# displayed and there is nothing more to display
Output:
1
7
8
3.45
Traceback (most recent call last):
File "<ipython-input-8-a92f27f8ecc2>", line 9, in <module>
next(my_iter) #Raises error since all the elements have been displayed and there is nothing more to display
StopIteration
P.S: Stay tuned, we will have posts that will give more details on how to build your own iterator and the concept of an infinite iterator.
Conclusion:
In this post, we understood what an iterator is, how it works, and how it can be used with different types of data structures.