Iterators-Iterables in Python

Iterators are collection of items and you can iterate through each item without any knowledge of the items stored in it and how they are stored. They can be list, dictionary or data generated from a sensor (which can be real time)

Let’s explain the above using an example:

Suppose we are in the dark room and on the floor, we have bricks for my son. Bricks of different size, color, does not matter now. Suppose we have 5 bricks like those. Those 5 bricks can be described as an object — let’s say bricks kit. We can do many things with this bricks kit — can take one and then take second and then third, can change places of bricks, put first brick above the second. We can do many sorts of things with those. Therefore this bricks kit is an iterable object or sequence as we can go through each brick and do something with it. We can only do it like my little son — we can play with one brick at a time. So again I imagine myself this bricks kit to be an iterable.

Now remember that we are in the dark room. Or almost dark. The thing is that we don’t clearly see those bricks, what color they are, what shape etc. So even if we want to do something with them — aka iterate through them — we don’t really know what and how because it is too dark.

What we can do is near to first brick — as element of a bricks kit — we can put a piece of white fluorescent paper in order for us to see where the first brick-element is. And each time we take a brick from a kit, we replace the white piece of paper to a next brick in order to be able to see that in the dark room. This white piece of paper is nothing more than an iterator. It is an object as well. But an object with what we can work and play with elements of our iterable object — bricks kit. (source of this example: https://stackoverflow.com/questions/9884132/what-exactly-are-iterator-iterable-and-iteration)

The retrieval of object from ab iterable object is managed by another object called as Iterator. The Iterator tracks the current value of the iterable object and helps to get the next value in the list.

Iterators can be:

1) Forward Iterators: Iterables which iterate in the forward direction without changing direction. As we said, the iterables can be series of list generated from a sensor which can be never ending of infinite.

2) Reverse Iterator: Opposite of forward iterators, these iterate in the backward direction or reverse direction.

Sample code for Advancing an Iterator: (printing all the even numbers)

  • The __init__() method is a class constructor and is the first thing that gets executed when a class is called. It is used to assign any values initially that will be required by the class during the program execution. I have initiated the num variable with 2 here
  • The iter() and next() methods are what make this class an iterator
  • The iter() method returns the iterator object and initializes the iteration. Since the class object is itself an iterator, therefore it returns itself
  • The next() method returns the current value from the iterator and changes the state for the next call. We update the value of the num variable by 2 since we are only printing even numbers
  • StopIteration: To prevent the iteration to go on forever, we can use the StopIteration statement. In the __next__() method, we can add a terminating condition to raise an error if the iteration is done a specified number of times.

Creating Iterables:

Iterables can be list, dictionary, tuple or can be generated by generator object or generator functions.

creating different iterators

How iterators work:

  • Iterable object can be passed successfully to the build in iter function
  • Iter function calls a special function __iter__ on the object.
  • __iter__ returns the required iterator value.

Two forms of iter():

  1. Iterator = iter(iterable)
  2. Iterator = iter(callable, sentinel )

o Callable — in case of zero arguments, this is invoked once per itertion

o Sentinel — iteration end which the callable produces this value.

Example of first form if iterator:

The above code snipped shows the sentinel value as None which means that whenever next is called on this iterable, this will print the datetime value. And this loop is never ending as we did not specified any end.

Iterators are powerful tool in Python. However, no everyone is familiar with the details of iterators. Congrats on making it to the end of this article.

Thanks..!!

DE by profession