Generators in Python
Generators are a powerful feature in Python that allows you to create iterators. Iterators are objects in Python that allow iteration over a sequence of elements, which are stored as Lists, Dictionaries, Tuples, or sets.
Key Characteristics of Generators
- Memory Efficient
- Lazy Evaluator
- Ability to handle large Datasets.
- Use a Yield Statement Instead of the return statement.
Yield Statement controls the flow of execution. Instead of exiting the function as seen when return is used, the yield keyword returns the function but remembers the state of its local variables.
The function only runs when the next() function is called on the generator object. When the next() function is called, the function runs until it encounters a yield statement. The value after yield is returned to the caller, and the state of the function is saved. The next time next() is called, execution resumes from where it left off.
Return Statement is used to exit the function and return a value to the caller.
Code of Simple Function using Return Statement
def func(n):
num=0
result=[]
while(num<n):
result.append(num)
num+=1
return result
print(func(5))
Output: [0,1,2,3,4]
It returns the list of values simultaneously.
Code of Generator Function using Yield Statement
def func1(n):
num=0
while(num<n):
yield num
num+=1
c=func1(5)
print(next(c))
print(next(c))
print(next(c))
Output: 0 1 2
It generates values as needed by using the next function rather than creating a list of all values simultaneously.