Tuesday, 25 April 2017

Iterators in python

Python Iterators:


  • Iterator in python is simply an object that can be iterated upon,on top of the iterator object we can apply the iterations.
  • in order to get the iterator object on any class object that class should contain _ _iter_ _( ) method and _ _next_ _( ) method collectively called the iterator protocol.
  • we can get the iterator object on any class object by calling iter( ) function.
  • we can get the one by one element from the iterator object by calling next( ) function.
  • no elements are there in the iterator object  next ( ) function returns stopIterationException .
  • builtin containers in python like: list,tuple,string, ... are iterables.

Iterating Through an Iterator in Python:



my_list = [4, 7, 0, 3]

# get an iterator using iter()

my_iter = iter(my_list)

# iterate through it using next() 

print(next(my_iter))

print(next(my_iter))

print(next(my_iter))

print(next(my_iter))

print(next(my_iter))




4

7

0

3

Traceback (most recent call last):

  File "E:/python_practice/examples/iter.py", line 9, in 

<module>  print(next(my_iter))

StopIteration


By using For loop:

my_list=[4,7,0,3]

for item in my_list:

    print(item)


4

7

0

3


How for loop actually works?



for element in iterable:

    iter_obj = iter(iterable)

    while True:

        try:

            element = next(iter_obj)

        except StopIteration:

                break

Building your own iterator in python:


class powtwo:

    def __init__(self,max=0):

        self.max=max

    def __iter__(self):

        self.n=0

        return self

    def __next__(self):

        if self.n <= self.max:

            result= 2**self.n

            self.n +=1

            return result

        else:

            raise StopIteration

a=powtwo(4)

i=iter(a)

print(next(i))

print(next(i))

print(next(i))

print(next(i))

print(next(i))

print(next(i))

1
2
4
8
16
Traceback (most recent call last):
  File "E:\python_practice\examples\own iterator.py", line 21, in <module>
    print(next(i))
  File "E:\python_practice\examples\own iterator.py", line 13, in __next__
    raise StopIteration

StopIteration



class powtwo:

    def __init__(self,max=0):

        self.max=max

    def __iter__(self):

        self.n=0

        return self

    def __next__(self):

        if self.n <= self.max:

            result= 2**self.n

            self.n +=1

            return result

        else:

            raise StopIteration

for i in powtwo(4):

    print(i)



1
2
4
8
16

Advantages:

cleaner code.

iterators can work with infinite sequences.

iterators saver resources like memory management,power management,process management,....

for large data sets,iterators saves both time and space

No comments:

Post a Comment