Friday, March 15, 2013

Itertools chain function

Few examples are from the book Python standard library by example.

From the
Documentation====>The chain() function takes several iterators as arguments and returns a single iterator that produces the contents of all of them as though they came from a single iterator.


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.



#!usr/bin/env/python 
from itertools import * #chain function  
"""
From the
Documentation====>The chain() function takes several iterators 
as arguments and returns a single iterator that produces the contents of all of them as though they came from a single iterator.

"""
from itertools import *
#Example 1(with equal sized lists)
print "Equal Sized lists:"
for i in chain([1,2,3],['a','b','c']):
    print i,
    # ',' is for horizontal printing of output.

#Example 2:(with inequal size of lists)
print "\n inequal size of lists:"
for i in chain([1,2,3],['a','b']):
    print i,

#Example 3:Tuples and strings
print "\n For tuples and strings"
for i in chain((1,2,3),"Ajay kumar Medepalli"):
    #Ajay kumar Medepalli==>It's my name :P
    print i,



The output is shown in the screenshot

 Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

No comments:

Post a Comment