ITERATORS PART-1

Iterators in Python

Iterator in python is any python type that can be used with a ‘for in loop’. Python lists, tuples, dicts and sets are all examples of inbuilt iterators. These types are iterators because they implement following methods. In fact, any object that wants to be an iterator must implement following methods.

1.    __iter__ method that is called on initialization of an iterator. This should return an object that has a next or __next__ (in Python 3) method.

2.    next ( __next__ in Python 3) The iterator next method should return the next value for the iterable. When an iterator is used with a ‘for in’ loop, the for loop implicitly calls next() on the iterator object. This method should raise a StopIteration to signal the end of the iteration.

 

How an iterator really works in python

# Here is an example of a python inbuilt iterator

# value can be anything which can be iterate

iterable_value ='Geeks'

iterable_obj =iter(iterable_value)

  

whileTrue:

    try:

  

        # Iterate by calling next

        item =next(iterable_obj)

        print(item)

    exceptStopIteration:

  

        # exception will happen when iteration will over

        break

Output :

G

e

e

k

s

Below is a simple Python custom iterator that creates iterator type that iterates from 10 to given limit. For example, if limit is 15, then it prints 10 11 12 13 14 15. And if limit is 5, then it prints nothing.

# A simple Python program to demonstrate

# working of iterators using an example type

# that iterates from 10 to given value

  

# An iterable user defined type

classTest:

  

    # Cosntructor

    def__init__(self, limit):

        self.limit =limit

  

    # Called when iteration is initialized

    def__iter__(self):

        self.x =10

        returnself

  

    # To move to next element. In Python 3,

    # we should replace next with __next__

    def__next__(self):

  

        # Store current value ofx

        x =self.x

  

        # Stop iteration if limit is reached

        ifx >self.limit:

            raiseStopIteration

  

        # Else increment and return old value

        self.x =x +1;

        returnx

  

# Prints numbers from 10 to 15

fori inTest(15):

    print(i)

  

# Prints nothing

fori inTest(5):

    print(i)

Output :

10
11
12
13
14
15

Examples of inbuilt iterator types.

# Sample built-in iterators

  

# Iterating over a list

print("List Iteration")

l =["geeks", "for", "geeks"]

fori inl:

    print(i)

      

# Iterating over a tuple (immutable)

print("\nTuple Iteration")

t =("geeks", "for", "geeks")

fori int:

    print(i)

      

# Iterating over a String

print("\nString Iteration")    

s ="Geeks"

fori ins :

    print(i)

      

# Iterating over dictionary

print("\nDictionary Iteration")   

d =dict() 

d['xyz'] =123

d['abc'] =345

for i in d :

    print("%s  %d"%(i, d[i]))

Output :

List Iteration

geeks

for

geeks

 

Tuple Iteration

geeks

for

geeks

 

String Iteration

G

e

e

k

s

 

Dictionary Iteration

xyz  123

abc  345

 


Comments