Iterator and Iterables in Python

Iterator and Iterables in Python

We can use iterators and iterable using for loop,genators etc.Iterators are objects used to travesrse using loop.We can build our own iterators using __iter__ and __next__.
Topics to cover in this post:

    What are iterators and iterables in Python?
    Iterating using iterator in python & user defined Iterators
    Iterators in for loop

What are iterators and iterables in Python?

Iterators are objects used to travesrse using loop.Python iterator object must implement two special methods using __iter__() and __next__().

Iterables is collections of elements through which an iterator iterates.Python has few built-in iterables like list,tuple,string etc.

Iterating using iterator in python & user defined Iterators

We can use__iter__() and __next__() methods to iterate through an iterable.
__iter__() is a function returns itself every time the iteration occurs.
__next__() is used to move to next position and return the value present at that location.Once the end of iterable is reached then __next__() will raise an Exception called as StopIteration.
Example :

"""
Author : ITVoyagers (https://itvoyagers.in/)

Date :25th December 2018

Description : Program to use of iter() and next()
"""

>>> collection=['i','Love','python']  #defined an iterable of list type
>>> x=iter(collection) # x is an object of iter(), any variable name can be used in place of x
>>> print(next(x))  #use of next()
i
>>> print(x.__next__())  #calling next() with x obj
Love
>>> next(x) #next() without print as we are working on prompt
'python'
>>> print(next(x))
Traceback (most recent call last):
File "<pyshell#6>", line 1, in
print(next(x))
StopIteration
#exception is raised as iterator has reached till end of iterable.
>>>

Iterators in for loop

We can also iterate automatcally using for loop and without actually writing iter() and next().
We can use list,tuple,string,or range as iterable in for loop.
Syntax:

for iter_obj in iterable:

Here iter_obj is iterator object which moves in iterable
iterable can be anything like list ,tuples etc
Example :

"""
Author : ITVoyagers (https://itvoyagers.in/)

Date :25th December 2018

Description : Program to automate iterations using for loop(to print squares of numbers from 1 to 50
"""

for i in range(1,51):
print("squares of",i,"=",i**2)

Explanation:
i indicates iterator and range() provides iterable to traverse.
Example  for user defined iterator :

"""
Author : ITVoyagers (https://itvoyagers.in/)

Date :25th December 2018

Description : Program to create user defined iterator
"""
class squares:
    def __init__(self, max = 0):#max value till which iterator will move,by default it is set to 0
        self.max = max

    def __iter__(self):
        self.n = 0  #by default it is 0 but increment it with each iteration
        return self

    def __next__(self):
        if self.n <= self.max: 
            result = self.n**2 # num raise to 2
            self.n+= 1   #counter will increase by 1 
            return result
        else:
            raise StopIteration #exception will be raised once the iterator tries to cross max value

Output

>>> sq=squares(5) #creating object for class and passing max value
>>> i=iter(sq) #creating object for iter()
>>> next(i)
0
>>> print(next(i))
1
>>> print(i.__next__())
4
>>> next(i)
9
>>> next(i)
16
>>>
>>> next(i)
25
>>> next(i)
Traceback (most recent call last):
File "<pyshell#9>", line 1, in
next(i)
File "C:/Python34/for_square.py", line 18, in __next__
raise StopIteration #exception will be raised once the iterator tries to cross max value
StopIteration
>>> 

1 thought on “Iterator and Iterables in Python”

Leave a Comment