Python 3 Tutorial
Generators are way to create custom iterators. Generator are created using functions. Then How it is different from other functions, generator function uses yield statement. Built-in iterators has __itr__ and __next__ dunder methods implementation. for custom iterators, yield statement provides __itr__ method implementation and __next__ method implemention. and follows iterator protocol. i.e whenever for-loop asks for next item in the container, yield statement pause the function execution and return a value to the caller,and remember state of the object,again control comes back to the called function , this process continues until StopIteration exception is thrown
>>> def gen(): ... yield 1 ... yield 2 ... yield 3 ... >>> >>> for i in gen(): ... print(i) ... 1 2 3
>>> def gen(): ... lscores = [20,30,20,10,2,5] ... index = 0 ... while (len(lscores) != index): ... yield lscores[index] ... index=index+1 ... >>> gen()Reverse Iterator>>> >>> for i in gen(): ... print(i) ... 20 30 20 10 2 5
>>> def gen(): ... lscores = [20,30,20,10,2,5] ... index = len(lscores)-1 ... while ( index >= 0): ... yield lscores[index] ... index=index-1 ... >>> for i in gen(): ... print(i) ... 5 2 10 20 30 20 >>>
ADS