In [22]:
it = iter([1,2,3])

Each time we call next it return the next element. If there is not more elements, it raises StopIteration exception

In [23]:
next(it)
Out[23]:
1
In [24]:
next(it)
Out[24]:
2
In [25]:
next(it)
Out[25]:
3
In [26]:
next(it)
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-26-bc1ab118995a> in <module>()
----> 1 next(it)

StopIteration: 

The __iter__ method is what makes an object iterable.The return value of __iter__ is an iterator. It should have a next method and raise StopIteration when there are no more elements.

Problem 1: Write an iterator class reverse_iter, that takes a list and iterates it from the reverse direction. ::

In [29]:
class reverse_iter:
    def __init__(self, e):
        self.i = len(e)
        self.e = e
    def __iter__(self):
        return self
    def __next__(self):
        if self.i>0:
            self.i -=1
            return self.e[self.i]
        else:
            raise StopIteration()
In [30]:
my_iter = reverse_iter([1,2,3])
In [31]:
next(my_iter)
Out[31]:
3
In [32]:
next(my_iter)
Out[32]:
2
In [33]:
next(my_iter)
Out[33]:
1
In [34]:
next(my_iter)
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-34-94a4229f6542> in <module>()
----> 1 next(my_iter)

<ipython-input-29-34ba3955c638> in __next__(self)
     10             return self.e[self.i]
     11         else:
---> 12             raise StopIteration()

StopIteration: 

When next method run out of element it raised StopIteration.

Lets make use of sentinel and remember when providing sentinel the first argument of iter must be callable . Lets read a file till EOF

In [8]:
f = open("test.txt")
In [9]:
it = iter(f.readline, '')
In [10]:
next(it)
Out[10]:
'Welcome to Hackaholic\n'
In [11]:
next(it)
Out[11]:
'Hello this is python programming.\n'
In [12]:
next(it)
Out[12]:
'Python is a awesome language.\n'
In [13]:
next(it)
Out[13]:
'We are learning iterator right now.\n'
In [14]:
next(it)
Out[14]:
'Follow me till the end. \n'
In [15]:
next(it)
Out[15]:
'And have fun learning python.\n'
In [16]:
next(it)
Out[16]:
'Everyday there is someting new to learn.'
In [17]:
next(it)
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-17-bc1ab118995a> in <module>()
----> 1 next(it)

StopIteration: 

Lets do the above in pythonic way

In [23]:
f = open("test.txt")
In [25]:
print("".join((iter(f.readline, ''))))
Welcome to Hackaholic
Hello this is python programming.
Python is a awesome language.
We are learning iterator right now.
Follow me till the end. 
And have fun learning python.
Everyday there is someting new to learn.