Python Genertors

Python Generators:

Generators are functions that can be paused and resumed.
Unlike lists, they produce items one at a time and only when asked. 
So they are much more memory efficient.

Generator Functions:

A generator-function is defined like a normal function, but whenever it needs to generate a value, it does so with the yield keyword rather than return. If the body of a def contains yield, the function automatically becomes a generator function.

Example:

def GeneratorFunc():
yield 4
yield 5
yield 6

for value in GeneratorFunc():
print(value)

Output:
4
5
6


Application of generators:

Generators are used to create iterators, but with a different approach. Generators are simple functions which return an iterable set of items, one at a time, in a special way.

Post a Comment

0 Comments