Iterators Iteration protocol Infinite iterators Generators Generator expressions Relationship between iterator and generator Advantages
Iterators An iterator is an object which allows a programmer to traverse through all the elements of a collection, regardless of its specific implementation. 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 next() method which returns the next element of sequence.
Examples We use for statement for looping over a list. >>> for i in [ 1 , 2 , 3 , 4 ]: ... print i , ... 1 2 3 4
Examples If we use it with a string, it loops over its characters. >>> for c in "python" : ... print c ... p y t h o n
Examples If we use it with a dictionary, it loops over its keys. >>> for k in { "x" : 1 , "y" : 2 }: ... print k ... y x
Examples If we use it with a file, it loops over lines of the file. >>> for line in open ( "a.txt" ): ... print line , ... first line second line
Iteration protocol The built-in function iter takes an iterable object and returns an iterator. Each time we call the next method on the iterator gives us the next element. If there are no more elements, it raises a StopIteration .
Examples >>> x = iter ([ 1 , 2 , 3 ]) >>> x < listiterator object at 0x1004ca850> >>> x . next () 1 >>> x . next () 2 >>> x . next () 3 >>> x . next () Traceback (most recent call last): File < stdin > , line 1 , in <module> StopIteration
Examples class yrange : def __ init __ ( self , n ): self . i = self . n = n def __ iter __ ( self ): return self def next ( self ): if self . i < self . n : i = self . i self . i += 1 return i else : raise StopIteration () Iterators are implemented as classes. Here is an iterator that works like built-in xrange function.
Examples The __ iter __ method is what makes an object iterable . Behind the scenes, the iter function calls __ iter __ method on the given object. The return value of __ iter __ is an iterator. It should have a next method and raise StopIteration when there are no more elements.
Examples >>> y = yrange ( 3 ) >>> y . next () >>> y . next () 1 >>> y . next () 2 >>> y . next () Traceback (most recent call last): File < stdin > , line 1 , in <module> File < stdin > , line 14 , in next StopIteration
Infinite Iterators It is not necessary that the item in an iterator object has to exhaust. There can be infinite iterators (which never ends). We must be careful when handling such iterator.
Examples >>> a = iter ( InfIter ()) >>> next (a) 1 >>> next (a) 3 >>> next (a) 5 >>> next (a) 7 class InfIter : """Infinite iterator to return all odd numbers""" def __iter__(self): self.num = 1 return self def __next__(self): num = self.num self.num += 2 return num