User Tools

Site Tools


python:iterators

ITERATORS && GENERATORS

28.05.2009

In computer science, an iterator is an object that allows a programmer to traverse through all the elements of a collection, regardless of its specific implementation. An iterator is sometimes called a cursor, especially within the context of a database.Wiki Link

Python supports a concept of iteration over containers. This is implemented using two distinct methods; these are used to allow user-defined classes to support iteration. Sequences, described below in more detail, always support the iteration methods.

One method needs to be defined for container objects to provide iteration support iter

class MyIterator(object):
   # ... some code ....
 
   def __iter__(self):
       """Returns the iterator itself."""
       return self
 

Fibonacci example using an iterator:

#!/usr/bin/env python2.6
# -*- coding: utf8 -*-
 
# iterator example; uses Fibonacci numbers, so common in computer
# science examples: f_n = f_{n-1} + f_{n-2}, with f_0 = f_1 = 1
 
class Fibnum:
    def __init__(self):
        self.fn2 = 1 # "f_{n-2}"
        self.fn1 = 1 # "f_{n-1}"
 
    def next(self): 
        ''' next() is the heart of any iterator
        note the use of the following tuple to not only save lines of
        code but also to insure that only the old values of self.fn1 and
        self.fn2 are used in assigning the new values '''
        (self.fn1,self.fn2,oldfn2) = (self.fn1+self.fn2,self.fn1,self.fn2)
        return oldfn2
 
    def __iter__(self):
        return self
 
if __name__ == "__main__":
    fibob = Fibnum()
    for i in fibob:
        print i
        if i > 30: break

GENERATORS

Generators are a simple and efficient way to write code for functions who work and return a list of elements. Specific element is the yield directive. This allows to pause a function and return an intermediate result. The function saves the execution state and return at that point if necessary.

Fibonacci example with Generator

#!/usr/bin/env python2.6
# -*- coding: utf8 -*-
 
# iterator example; uses Fibonacci numbers, so common in computer
# science examples: f_n = f_{n-1} + f_{n-2}, with f_0 = f_1 = 1
 
def fibonacci():
    ''' fibonacci function using generator '''
    a, b = 0, 1
    while True:
        yield b
        a, b = b, a+b
 
 
fib = fibonacci()
for i in range(34):
    print fib.next()

Another generator example with 2 functions

#!/usr/bin/env python2.6
# -*- coding: utf8 -*-
 
# generator exemplified
 
def printing(values):
    for value in values:
        print "Printing function: we deal with value %d" % value
        yield value
 
 
def multiplying(values):
    for value in values:
        print "Multiplying function: multiply by 3 %d" % (value * 3)
        yield value * 3
 
 
numbers = [12, 34, 5, 2, 56]
res = multiplying(printing(numbers))
 
print "Step 1"
res.next()
 
print "Step 2"
res.next()
 
print "Step 3"
res.next()


Generator example with yield and send()

send() is like next() but makes the yield to return the value passed. In the next code what variable will get the message passed to send.

#!/usr/bin/env python2.6
# -*- coding: utf8 -*-
 
# generator exemplified yield and send
 
def shout():
    print "First message is here"
    while True:
        what = (yield)
        print "You said %s" % what
 
s = shout()
 
s.next()
s.send("Hello there...")
s.send("Is there anybody there?")
s.next() # this will display You said None

python/iterators.txt · Last modified: 2013/03/16 17:40 (external edit)