Python Iterators


An iterator is an object containing a number of countable values.

An iterator is an object to which iteration is possible, meaning all the values can be crossed.

In Python, an iterator is an art object that implements a protocol to the iterator that consists of the __iter__() and __next__ methods.

You can also search for these topics, python iterators example, how to use the next iterators in python, check the python product iterators, advantages of python iterators, define the index using python iterators, python iterators best practices, iterators back to start in python, how to count the python iterators, python delete iterators.

Iterator vs Iterable

Lists, tuples, dictionaries and sets are all objects which can be iterated. You can get an iterator from them are iterable containers.

The iter() method is used to retrieve an iterator from any objects :

Example 1 :- Return a tuple iterator and print out each value :

mytuple = ("aa", "bb", "cc")
myit = iter(mytuple)

print(next(myit))
print(next(myit))
print(next(myit))

Output :-

aa
bb
cc

Strings are also can work with iterable objects.

Example 2 :- Make a string iterable objects and print each character one by one :

mystr = "Hi"
myit = iter(mystr)

print(next(myit))
print(next(myit))

Output :-

H
i

You can also search for these topics, python iterator vs iterable between sequence, python collection Iterator vs Iterable, check Iterator vs Iterable using python, differenciate the Iterator vs Iterable in python, example for python Iterator vs Iterable, working of python function with Iterator vs Iterable.

Looping Through an Iterator

A for loop can also be used to iterate via an iterable object :

Example 1 :- Iterate the values of a tuple :

mytuple = ("aa", "bb", "cc")

for x in mytuple:
  print(x)

Output :-

aa
bb
cc

Example 2 :- Iterate the characters of a string :

mystr = "Hi"

for x in mystr:
  print(x)

Output :-

H
i

The for loop generates an iterator object and executes for each loop the next() method.

You can also search for these topics, python looping through an iterator by value, Looping Through an Iterator collection in python, how to change the python Looping Through an Iterator, count the Looping Through an Iterator in python, python doesn't work with iterator with looping, example for Looping Through an Iterator using python, python infinite and increase iterator with looping.

Create an Iterator

You have to implement __iter__() and __next__() methods into your object in order to generate an object/class as the iterator.

As you know, in the Python Classes/Objects chapter, all classes contain __init__() function that lets you initialise when creating the object.

The __iter__() method works similar, operations may be performed (initialising etc.), but the object iterator must always be returned.

You can also use the __next__() method and have to return the next item in the series.

Example :- Create an iterator which return numbers from 1 and increases each series by one sequence (returns 1,2,3 etc.) :

class MyNumbers:
  def __iter__(self):
    self.a = 1
    return self

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

myclass = MyNumbers()
myiter = iter(myclass)

print(next(myiter))
print(next(myiter))
print(next(myiter))

Output :-

1
2
3

You can also search for these topics, python create an iterator from a list, how to Create an Iterator object in python, python Create an Iterator best practice, example for python Create an Iterator, key value of an Iterator to create python methods, use of iterator to create next previous with python, python to check the empty iterator, Example for python Create an Iterator.

StopIteration

If you have enough next() statement or were using it in a loop, the preceding example would run for loop.

We can use the StopIteration statement to prevent this iteration from going forever.

In the method __next__() termination condition can be added to make an error when the iteration is made several times :

Example :- Stop after 5 iterations

class MyNumbers:
  def __iter__(self):
    self.a = 1
    return self

  def __next__(self):
    if self.a <= 5:
      x = self.a
      self.a += 1
      return x
    else:
      raise StopIteration

myclass = MyNumbers()
myiter = iter(myclass)

for x in myiter:
  print(x)

Output :-

1
2
3
4
5

You can also search for these topics, python stopiteration error, example for python stop iteration, use the StopIteration next method with python, python to generate the iteration to stop, how to StopIteration the catch a python, python exception to stopiteration, working of function to python stop iteration, python to stop handling iteration, Example for python to stop iteration.