In this article, we will learn how to use generators in our programs using python.
Introduction:
Python generators are a simple way of creating iterators. All the work we mentioned above is automatically handled by generators in Python.
Simply speaking, a generator is a function that returns an object (iterator) that we can iterate over (one value at a time).
It is a lengthy process to create iterators. That’s why the generator plays an essential role in simplifying this process. If there is no value found in iteration, it raises StopIteration exception.
Create a generator function:
A generator function is defined as a normal function, but whenever it needs to generate a value, it does so with the keyword called yield rather than return. If the body of a def contains yield, the function automatically becomes a generator function.
Example:
# A generator function that yields 1 for first time,
# 2 second time and 3 third time
def simpleGeneratorFun():
yield 1
yield 2
yield 3
# Driver code to check above generator function
for value in simpleGeneratorFun():
print(value)
Generators with a loop:
Normally, generator functions are implemented with a loop having a suitable terminating condition.
Let’s take an example of a generator that reverses a string.
Example:
def rev_str(my_str):
length = len(my_str)
for i in range(length - 1, -1, -1):
yield my_str[i]
# For loop to reverse the string
for char in rev_str("hello"):
print(char)
Output:
o l l e h
In this example, we have used the range()
function to get the index in reverse order using the for-loop.
Generator Expression:
We can easily create a Generator expression without using any user-defined functions, it is similar to creation of anonymous functions with list comprehension.
Example:
list = [1,2,3,4,5,6]
z = (x**3 for x in list)
print(next(z))
print(next(z))
print(next(z))
print(next(z))
Output
1 8 27 64