Iterators
Essentially, an iterator is an object that has a next () method
Iterators can be created using the built-in iter method
>>> i = iter ('abc')>>> i.next ()'a '>>> i.next ()'b'>>> i.next () ' C '
To create iterators for classes available __iter__ and next ()
classFib (object):def __init__(self): SELF.A, self.b= 0, 1#Initialize two counters A, B def __iter__(self):returnSelf#The instance itself is an iterative object, so it returns itself defNext (self): SELF.A, self.b= self.b, SELF.A + self.b#Calculate Next Value ifSELF.A > 100000:#conditions for exiting a loop Raisestopiteration (); returnSelf.a#returns the next value forNinchFib ():PrintN-------------------------------11235...4636875025
Generator
The generator can be iterated, but it can only be read once
for in range (3)) -in GT: ... Print (i) 0 for inch g: ... Print (i)
yield
# When you call this function, the code inside the function does not execute immediately, This function simply returns a generator object def CreateGenerator (): MyList = range (3 for i in MyList: yield i*i >>> for i in Mygenerator: print I0 14> >> for i in mygenerator: # is also callable only once print i
2015-05-26
Python iterators and generators