Python Iterators


Python Iterators

An iterator is an object that contains a fixed number of values.

An iterator is something that can be repeated over it, which means you can disconnect at all values.

Technically, in Python, an iterator is a device that uses an iterator protocol, which combines __iter __() and __ next __() methods.


Iterator vs Iterable

Lists, tuples, dictionaries, and sets are all readable. They are readable containers from which you can find the iterator.

All of these items have an iter() method used to locate the iterator:


Example

Return an iterator from a tuple, and print each value:

mytuple = ("apple", "banana", "cherry")
myit = iter(mytuple)

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

Even the character units are readable, and can replace the iterator:


Example

Strings are also iterable objects, containing a sequence of characters:

mystr = "banana"
myit = iter(mystr)

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


Looping Through an Iterator

We can also use the for loop to repeat over and over again:


Example

Iterate the values of a tuple:

mytuple = ("apple", "banana", "cherry")

for x in mytuple:
  print(x)


Example

Iterate the characters of a string:

mystr = "banana"

for x in mystr:
  print(x)

The for loop actually creates a duplicate object and uses the following method () for each loop.


Create an Iterator

To create an object / class as an iterator you must use __iter __() and __next __() methods in your object.

As you learned in the Python Classes / Objects chapter, all classes have a function called __init __(), which allows you to perform a specific task when something is created.

The way __iter __() does the same, you can do tasks (startup etc.), but you should always return the repetitive object itself.

The __next __() method allows you to perform tasks, and you must return the following item in sequence.


Example

Create an iterator that returns numbers, starting with 1, and each sequence will increase by one (returning 1,2,3,4,5 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))
print(next(myiter))
print(next(myiter))


StopIteration

The example above would be permanent if you had enough of the following statements (), or if it was a for applied to a loop.

To prevent the recurrence from happening permanently, we may use the StopIteration statement.

In the __next __() method we can add a termination rule to suggest an error if the repetition is repeated several times:


Example

Stop after 20 iterations:

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

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

myclass = MyNumbers()
myiter = iter(myclass)

for x in myiter:
  print(x)