Audvik Labs

Understanding about Python Iterator

Introduction

An iterator is an object that contains a countable number of values. An iterator is an object that can be iterated upon, meaning that you can traverse through all the values.
Technically, Python iterator is an object which implements the iterator protocol, which consist of the methods iter() and next()

Create an Iterator

To create an object/class as an iterator you have to implement the methods iter() and next() to your object.
The iter() method acts similar, you can do operations (initializing etc.), but must always return the iterator object itself.
The next() method also allows you to do operations, and must return the next item in the sequence.

Insights

Iterators are everywhere in Python. They are elegantly implemented within for loops, comprehensions, generators etc. but are hidden in plain sight.
Iterator in Python is simply an object that can be iterated upon. An object which will return data, one element at a time.
Technically speaking, a Python iterator object must implement two special methods, iter() and next(), collectively called the iterator protocol.
An object is called iterable if we can get an iterator from it. Most built-in containers in Python like: list, tuple, string etc. are iterables.
The iter() function (which in turn calls the iter() method) returns an iterator from them.

Iterator and Iterable

Iterable is an object, which one can iterate over. It generates an Iterator when passed to the iter() method. Lists, tuples, dictionaries, strings and sets are all iterable objects. They are iterable containers that you can convert into an iterator.
Note that every iterator is also an iterable, but not every iterable is an iterator. For example, a tuple is iterable, but it is not an iterator. An iterator can be created from an iterable by using the function iter(). Thus, when we pass this tuple to an iter() function, we will get an iterator. Actually, this is possible because the class of an object has a method iter(), which returns an iterator.

Built-in Iterators in Python

There are some compelling built-in Iterators in Python, which will be very useful for the programmers for effective looping, and it also speeds up the code execution.
These built-in iterators are available in the module ‘itertools’ in Python. This module implements several iterative building blocks.
Here are a few useful iterators in Python accumulate(iter, func):
This accumulate iterator will take two parameters. These two parameters are nothing but an iterable target and function, which will be followed at each iteration of value in target.
If the input iterable is empty, then the output iterable also will be empty. If no function is passed, addition takes place by default.
Chain (iter1, iter2…):
Chain iterator function is used to print all the values in iterable one after another mentioned in the function parameters.
Example
In this example, you will create an iterator that returns odd numbers starting from 1. class randomNumbers:
def iter(self): self.a = 1
return self
def next(self): x = self.a
self.a += 2
return x
myclass = randomNumbers () myiterator= iter(myclass)

print(‘Iterator in python’) print(next(myiterator)) print((‘Iterator in python’) print(next(myiterator)) print((‘Iterator in python’)
Here, the randomNumbers is an object/class which is being implemented with two methods iter() and next() for an iterator.
Now, execute this program to see the output.

Infinite Python3 Iterator

It is indeed possible to create an iterator in Python that never exhausts. The iter() function can take another argument, called the ‘sentinel’, it keeps a watch.
As long as the first value isn’t the same as the sentinel, the Python iterator does not exhaust.
We know that the int() function, without a parameter, returns 0.

>>>int()
Now, we call iter() on two arguments- int and 1.
>>>a=iter(int,1)
This Python iterator will never exhaust; it is infinite. This is because 0 is never equal to 1.
>>>next(a)

>>> next(a)

>>> next(a)

>>> next(a)

>>> next(a)

And so on.

To create an infinite Python iterator using a class, take the following example.

>>>class Even:
def _iter_(self):
self.num=2
return self

def _next_(self):

num=self.num

self.num+=2

return num
>>>e=Even()

>>> i=iter(e)

>>> next(i)

Output
2
next(i)

Output
4
next(i)

Output
6
next(i)

Output
8
num=self.num self.num+=2 return num

This python iterates on even numbers beginning at 2, ending nowhere. So, you must be careful to include a terminating condition.

Benefits of Python Iterator

An iterator in python saves resources. To get all the elements, only one element is stored in the memory at a time. Unlike this, a list would have to store all the values at once.

Conclusion

An iterator is a basic object that can be iterated over in Python. A data-returning object that returns data in one-at-a-time increments. An iterator is a set of countable values. Iterators are objects that can be iterated over, which means you can go through all of the values. A Python object that implements the iterator protocol, which includes the methods _iter_() and_ next_, is known as an iterator ().Iterators have the advantage of being energy efficient. You don’t have to memorize the entire number system to get all the odd numbers. You can have infinite objects in finite memory.

Leave a comment

Your email address will not be published. Required fields are marked *