Question:
Write a python program to show the difference in zip() and izip() function
Explanation:
zip() is a standard library which combines elements into tuples.
The izip() function works the same way, but it returns an iterable object for an increase in performance by reducing memory usage.
We can directly print the list returned by zip() but, we cannot directly print an iterable object. We need to use next(iterable_object) or a loop.
Lists are stored in memory so they have the advantage of faster access times over Iterable Object whose contents are not entirely stored in memory but fetched on-demand instead.
Program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
from itertools import izip #import izip to use it in the program list1=[1,2,3] list2=['a','b','c'] print "PRINTING INITIAL LISTS" print list1 print list2 x=zip(list1,list2) print "\n\nzip() PERFORMED" #zip() combines elements of list1 and list2 into tuples and returns a list of tuples which you can directly print print "PRINTING LIST OF TUPLES" print x x=izip(list1,list2) print "\n\nizip() PERFORMED" #izip() does almost same thing as zip() but it returns a iterlist.izip object which is iterable using next() or using loops print x #cant print contents of iterable object directly print "\nUSING LOOP TO PRINT CONTENTS OF izip OBJECT" for i in x: print i |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
PRINTING INITIAL LISTS [1, 2, 3] ['a', 'b', 'c'] zip() PERFORMED PRINTING LIST OF TUPLES [(1, 'a'), (2, 'b'), (3, 'c')] izip() PERFORMED <itertools.izip object at 0x2ae4fc5dcb48> USING LOOP TO PRINT CONTENTS OF izip OBJECT (1, 'a') (2, 'b') (3, 'c') |
Leave a Reply