Introduction to Iterators

Tip: The iterator is an implementation of the iterator protocol. This protocol contains the methods __next__() and __iter__(). In this article, we will learn about python iterators and also discuss and use these protocol functions.

Before moving ahead, let’s understand the difference between iterable and iterator

Iterable vs Iterator

Sets, Dictionaries, Tuples, and Lists are all iterable objects. You can get an iterator from these iterables as they are containers of it. All these iterables provide the iter() method which is used to get an iterator of these objects.

Example

myFruits = ("Grapes", "Apples", "Mangoes")
myiterator = iter(myFruits)

print(next(myiterator))
print(next(myiterator))
print(next(myiterator))

In this example, we get the iterator of each tuple and print it using the __next__() method.

We can also access an iterator out of the string because it’s also an iterable object.

Example

str = "Apple"
myiterator = iter(str)

print(next(myiterator))
print(next(myiterator))
print(next(myiterator))
print(next(myiterator))
print(next(myiterator))

In this example, we get the iterator of the string containing “Apple”. And then, we use the next operator to print each of these iterators which is pointing to the current character in the string.

Looping through Iterator

In this section, we will use the loops with the iterators. The next() operator in the previous examples moves the iterator to point to the next item in the iterator. However, the loop automatically increments the iterator object till the end or length of the iterator.

Example

tuple = ("Banana", "Grapes", "Apples")

for x in tuple:
  print(x)

In the above example, we use for loop to iterate through the tuple and print each value. Let's apply the for loop on the string.

Example
str = "Apple"

for x in str:
  print(x)

You must execute these examples and check the output. You can also first use the next() method to print the output and then use the for loop and verify if both methods produce the same output.

Note: The for loop create an iterator object and calls the next() method upon each iteration.

In the next section, we will learn how to create your own iterator in python.

Create an Iterator

As we have learned in the Python Classes article that all the classes contain __init__() function, which can be used to initialize the object when it is being created.

So, keeping this in view, to create a class/object as an iterator, we need to implement the __iter__() and __next__() methods to our object.

The __next__() method allows to perform operations and should return the next element in the sequence.

The __iter__() method also allows performing operations like initializing and should return the iterator object itself.

Example

class MyIterator:
  def __iter__(self):
    self.num = 1
    return self

  def __next__(self):
    var = self.num
    self.num += 1
    return var

obj = MyIterator()
iter = iter(obj)

print(next(iter))
print(next(iter))
print(next(iter))
print(next(iter))
print(next(iter))

In this example, we create our own iterator that returns the number. We initialize the number from 1 and this task is carried out in the __iter__() method. Then we implement the __next__() method to increment the number by 1.

You must execute this example to check the output. You must implement some other iterables as practice.

Upon the execution of the above example, you will notice that the program would never stop the execution because we have not stopped the iteration. We need to stop the iteration by using StopIteration statement.

Example

class MyIterator:
  def __iter__(self):
    self.num = 1
    return self

  def __next__(self):
    if self.a <= 10:
      var = self.num
      self.num += 1
      return var
   else:
      raise StopIteration


obj = MyIterator()
iter = iter(obj)

for x in iter:
  print(x)

In the above example, we used the if condition in the __next__() method to check if the current number is less than or equal to 10 and used StopIteration statement in the else statement.

You should execute this program to check if the iteration now stops when the number is 10.

Categorized in: