Concepts of Iterators & Generators

What is Iterator in Python:

As a python guy aware of it already right! Not like that let see what’s happening.

Directly or indirectly u already used iterators in your day by day programming confusing!!!

We are using for loop right !!, for internally calling iter object only.

As usual need definition.

Iterator:

According to Wikipedia, an iterator is an object which allows a programmer to traverse through all the elements of a collection, regardless of its specific implementation.

In Python programming language, an iterator is an object which implements the iterator protocol. The iterator protocol consists of two methods. The __iter__() method, which must return the iterator object and the next() method, which returns the next element from a sequence.

Python has several built-in objects, which implement the iterator protocol. For example lists, tuples, strings, dictionaries or files.

str = "formidable"

for i in str:
   print i,

print

it = iter(str)

print it.next()
print it.next()
print it.next()

print list(it)
In the code example, we show a built-in iterator on a string. In Python a string is an immutable sequence of characters. The iter() function returns an iterator on object. We can also use the list() or tuple() functions on iterators. 

O/P
f o r m i d a b l e
f
o
r
['m', 'i', 'd', 'a', 'b', 'l', 'e']

Iterators have several advantages:

  • Cleaner code
  • Iterators can work with infinite sequences
  • Iterators save resources

By saving system resources we mean that when working with iterators, we can get the next element in a sequence without keeping the entire dataset in memory.

Sample file opening code

#!/usr/bin/python

# wantme2.py

f = open('ifyouwantme', 'r')

for line in f:
   print line,

f.close()

Implement Our own Iterator Object

class seq14:
   def __init__(self):
      self.x = 0

   def next(self):
      self.x += 1
      if self.x > 14:
         raise StopIteration
      return self.x**self.x

   def __iter__(self):
      return self


s = seq14()

for i in s:
   print i

The StopIteration exception will cease the for loop.

Generators

In general, a generator is a special routine that can be used to control the iteration behaviour of a loop. A generator is similar to a function returning an array. A generator has parameters, it can be called and it generates a sequence of numbers. But unlike functions, which return a whole array, a generator yields one value at a time. This requires less memory. (Wikipedia)

Generators in Python:

  • Are defined with the def keyword
  • Use the yield keyword
  • May use several yield keywords
  • Return an iterator

Ex code:

def gen():
   x, y = 1, 2
   yield x, y
   x += 1
   yield x, y


it = gen()

print it.next()
print it.next()

try:
   print it.next()
except StopIteration:
   print "Iteration finished"

Explanation:

As we can see, a generator is defined with a def keyword, just like normal functions. 
We use two yield keywords inside the body of a generator. Now it is important to understand, 
how actually the yield keyword works. It exits the generator and returns a value. 
Next time the next() function of an iterator is called, 
we continue on the line following the yield keyword. Note that the local variables are 
preserved throughout the iterations. 
When there is nothing left to yield, a StopIteration exception is raised. 

One More Example:

import time
import sys

def fib():
   a, b = 0, 1
   while True:
      yield b
      a, b = b, a + b


iter = fib()

try:
   for i in iter:
      print i,
      time.sleep(1)
      sys.stdout.flush()
except KeyboardInterrupt:
   print "Calculation stopped"

Note :
From Python3 onwards everything is related iterator and generator only
i.e every object return iterator or generator as a result.

Referrer link :
http://zetcode.com/lang/python/itergener/

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s