In Python,Generators are simple functions which return an iterable set of objects, with a sequence of values in a special way. It is a simple way of creating iterators but with a different approach. It use the Python yield keyword instead of return
. It can be used in a for loop.
Generators used to control the iteration behaviour of a loop. It is similar to a function returning an array. A generator has parameter, which can be called and it generates a sequence of numbers.
As function, used to return a whole array but, generator yields one value at a time which requires less memory.
Generator functions allow us to declare a function that behaves just like an iterator, allowing programmers to make an iterator in a fast, easy, and clean way. An iterator is an object that can be iterated or looped upon. It is used to abstract a container of data to make it behave like an iterable object.
Generators are very easy to implement, but difficult to understand.
Example:
def Generator():
print("Name:")
yield "abc"
x = Generator()
print(next(x))
Output:
Name:
'abc'