Building an iterator in Python takes a lot of effort. We must create a class containing the methods __iter__()
and __next__()
, maintain track of internal states, and raise StopIteration
when no values are to be returned. Please refer python iterators to know details.
This is both lengthy and confusing. In such cases, the generator comes to the rescue.
Iterators can be easily created with Python generators. All of the work indicated above is completed automatically via Python generators.
The functions that return the traversal object and are used to generate iterators in Python are known as generators. It goes through all of the objects at once. The generator can also be an expression in which syntax is similar to the list comprehension in Python.
How to Create Generator function
In Python, creating a generator is pretty simple. It’s similar to a regular function declared with the def
keyword, but instead of return, it uses the yield
keyword. Or, to put it another way, every function that has a yield statement in its body is automatically converted to a generator function. Consider the following illustration:
def printNum():
count = 1
while count <= 5:
yield count
count +=1
values = printNum()
print(values)
for i in values:
print(i)
Output : <generator object printNum at 0x000001A3229520A0> 1 2 3 4 5
yield vs. return
The yield
statement is in responsible for managing the generator function’s flow. It yields to the caller and pauses the function execution by storing all states. When a subsequent function is called, it restarts execution. In the generator function, we can use the multiple yield statement.
The return
statement returns a value and ends the function, and the function can only have one return statement.
Generator Expression
Without using a user-defined function, we can easily generate a generator expression. The generator’s expressions create an anonymous generator function, similar to how the lambda function creates an anonymous function.
Generator expressions are represented similarly to Python list comprehensions. The only difference is that round parenthesis replace square brackets. The generator expression calculates one item at a time, whereas the list comprehension calculates the full list.
Example :
list = [1,2,3,4,5]
# List Comprehension
z = [x**3 for x in list]
# Generator expression
a = (x**3 for x in list)
print(a)
print(z)
Output : <generator object <genexpr> at 0x01AABDW8> [1, 8, 27, 64, 125]
List comprehension returned a list of cubes of elements in the above programme, whereas generator expression returned a reference to the calculated value. Instead of using a for loop, we can use the generator object’s next()
method. Consider the following scenario:
list = [1, 2, 3, 4]
z = (x ** 3 for x in list)
print(next(z))
print(next(z))
print(next(z))
print(next(z))
Output : 1 8 27 64
Difference between Generator function and Normal function
- Normal function contains only one return statement whereas generator function can contain one or more yield statement.
- When the generator functions are called, the normal function is paused immediately and control transferred to the caller.
- Local variable and their states are remembered between successive calls.
- StopIteration exception is raised automatically when the function terminates.
That is it for today, hope it helps.
If you have any suggestion for this article please make a comment in comment section below.
—
If you like this article, you can buy me a coffee. Thanks!
That means you’ll get the idea some new features and from access to additional channels where you can win visibility, without having to make sense of some complicated, guide migration process.