Iterators In Python

introduction-to-programming

Iterators in python:

Iterators in python is one of the simple and strong features of python. We already know that in python everything's an object. So, iterator is also a python object, which has a special method called "next". In python iterator acts like a container. When we call method "next" on the iterator object. It will creates and return the objects onfly. After returning the object it will longer available to access again. Python provides the built-in keyword "next". when we call the "next" with iterator object it will call the object method "next" which will return the object onfly.

usage of iterators in python

We can convert any object to an iterable object if only if it has a method "iter" implemented. To convert a object to an iterable object we need to call the python's built-in function "iter" with the object as an argument. It will call the "iter" method which is responsible to return iterable objects.

Example:

class Fibonacci:
    def __init__(self, limit):
        self.limit = limit
        self.counter = 0
        self.fib_data = []

    def __iter__(self):
        return self

    def next(self):
        self.counter += 1
        if self.counter > self.limit:
            raise StopIteration

        if len(self.fib_data) < 2:
            self.fib_data.append(1)
        else:
            self.fib_data = [
                self.fib_data[-1], self.fib_data[-1] + self.fib_data[-2]
            ]
        return self.fib_data[-1]
# Case1
for i in Fibonacci(3):
    print(i)
# Output:
# 1
# 1
# 2

# Case2
iter_obj = Fibonacci(3)
print(next(iter_obj))
print(next(iter_obj))
print(next(iter_obj))
print(next(iter_obj))
# Output:
# 1
# 1
# 2
# Traceback (most recent call last):
#  File "fibonacci.py", line 35, in <module>
#    print next(iter_obj)
# StopIteration
In above code we have created a fibonacci iterator it will generate first 'n' number of fibonacci numbers. When we call method next on the fibonacci iterator object it will return the fibonacci number.In case2 output we got "StopIteration" Error because it does not satisfy the condition in code. In similar manner python's built in function "range" is implemented. Python's built in structures like list, tuple, dict, etc. have methods "iter", "next". So, that we can convert them into iterators by using python's built-in function "iter".

Lets see usage of iterators with python builtin methods

# convert list to iterable object
l = [1,2,3]
iter_obj = iter(l)
print(iter_obj.next())
# Output: 1
# convert dict to iterable object
d = {1:2, 3:4}
iter_obj = iter(d)
print(iter_obj.next())
# Output: 1
# convert list to iterable object
t = (1,2,3)
iter_obj = iter(t)
print(iter_obj.next())
# Output: 1
If we want to use the objects onfly then it's a good approach to use iterators. If we want to the past results also then we have to use data structures like lists, tuples, etc.