1.

What are generators in Python?

Answer»

Generators are functions that return an iterable collection of items, one at a time, in a SET manner. Generators, in general, are used to create iterators with a different approach. They employ the use of YIELD keyword rather than return to return a generator object.
Let's try and build a generator for FIBONACCI numbers -

## generate fibonacci numbers UPTO ndef fib(n): p, q = 0, 1 while(p < n): yield p p, q = q, p + qx = fib(10) # create generator object ## iterating using __next__(), for Python2, use NEXT()x.__next__() # output => 0x.__next__() # output => 1x.__next__() # output => 1x.__next__() # output => 2x.__next__() # output => 3x.__next__() # output => 5x.__next__() # output => 8x.__next__() # error ## iterating using loopfor i in fib(10): print(i) # output => 0 1 1 2 3 5 8


Discussion

No Comment Found