Python

Python Iterator

The “Iterator” and “Iterable” are two common terms that are often utilized in Python programming. The iterator is an object that can be iterated upon and retrieved one value at a time, while the iterable is any sequence, such as a list, tuple string, etc. that we can use to create the iterator object.

This guide covers/explains the below topics:

What is a Python Iterator?

In Python, the “iterator” is an object that is utilized to iterate through the data collection, such as lists, tuples, sets, and dictionaries. It is an object that contains the countable values number and can be traversed to access each value one at a time.

Iterator Class Methods

An iterator object consists of the methods “__iter__()” and “__next__()” methods that are utilized for implementing iterator protocol.

__iter__() Method

The “__iter__()” method is called when an iterator is created from an object, it will retrieve the iterator object itself.

__next__() Method

The “__next__” method is called when the next value of the iterator is requested. It will return the next value in the sequence, or raise a “StopIteration” exception if there are no more values.

Difference Between Iterator vs Iterable

The “iterable” is an object that can be iterated through, in simple words, it can produce an iterator when passed to the “iter()” method. Iterable objects consist of dictionaries, sets, lists, tuples, and even strings. The iterable holds the data that we want to iterate/loop through a single value at a time.

On the other hand, the “iterator” is an object that is utilized to iterate through/over an iterable object using the “__next__()” method. It can retrieve the next item of the object and introduce a “StopIteration” error/exception when there are no more items present.

Note: All iterators are iterable, but not all iterable are iterators.

In the below example code, we first created the list (iterable object) and passed it to the “iter()” method. Next, the “iter()” method converts the list iterable into an iterator object. Finally, we can use the “next()” method to print the iterator objects one by one:

list1 = ["Joseph", "Anna", "Lily"]
print(list1, '\n')
iter1 = iter(list1)

print(next(iter1))
print(next(iter1))
print(next(iter1))

The snippet shows the iterable and iterator objects:

Example 1: Looping Through an Iterator

To loop through an iterator, we can use the “for” loop. First, we create the list iterable object and pass it to the “iter()” method. After that, the “iter()” method creates an iterator object. The for loop iterates over the iterator object and retrieves the element of iterable:

list1 = ["Joseph", "Anna", "Lily"]
print(list1, '\n')
iter1 = iter(list1)

for i in iter1:
    print(i)

The above code retrieves the below output:

Example 2: Looping Through a String

Here, we initialize the string iterable object. The string value can also be an iterator over using the “iter()” method. After creating an iterator object, we retrieve the substring or character of the string by iterating over the iterator object using the for loop:

list1 = "Python"
print(list1, '\n')
iter1 = iter(list1)

for i in iter1:
    print(i)

The following snippet shows the above code output:

Example 3: Creating a Custom Iterator

In this code, we first define the class named “number” that is used to implement the “iterator protocol”. To create a custom iterator object we need to define the two methods in the class “__iter__” and “__next__”. Here in this case, the “__iter__” method sets the attribute “self.a” to “1” and retrieves the “self”. The “__next__” method returns the current value of the “self.a” and then increments it by “1”. Lastly, we create the instance and pass it to the “iter()” method, which retrieves an iterator object. To get the value of the iterator the “for” loop is the iterator over the iterator object:

class number:
    def __iter__(self):
      self.a = 1
      return self
   
    def __next__(self):
        x = self.a
        self.a += 1
        return x

z1 = number()
iter1 = iter(z1)

for i in iter1:
    print(i)

The below snippet shows that the loop will run indefinitely, as the iterator never raises a “StopIteration” exception:

Example 4: Stopping Custom Iterator Using StopIteration Statement

To stop the infinite iterator object, we utilize the “StopIteration” statement in the Python program. In the next method, the if-else statement is used to create the condition that will display the iterator object until the “10” value is reached:

class number:
    def __iter__(self):
      self.a = 1
      return self
   
    def __next__(self):
        if self.a <= 15:
            x = self.a
            += 1
            return x
        else:
            raise StopIteration


z1 = number()
iter1 = iter(z1)

for i in iter1:
    print(i)

Here in the below output, the iterator stopped at the specified iterator value:

Conclusion

In Python, iterators are utilized to iterate the iterable object i.e. list, tupe, string, etc. Next, we retrieved their element value by looping through it. The “__iter__()” method and “__next__()” method are defined inside the class to create the iterator object in Python. We can stop the infinite iterator object while retrieving the value using the “StopIteration” statement. This guide explored Python iterators with several examples.

About the author

Haroon Javed

Hi, I'm Haroon. I am an electronics engineer and a technical content writer. I am a tech geek who loves to help people to the best of my knowledge.