How to create a generator in Python?

Creating a generator is easy in Python. You can create a generator just by defining a function with a yield statement instead of a return statement. If a function contains at least one yield statement, it becomes a generator function. yield and return statements will return some value from a function. Here is an example:

def my_gen():
n = 1
print('This is printed first')
yield n
n += 1
print('This is printed second')
yield n
n += 1
print('This is printed at last')
yield n
for item in my_gen():
print(item)

Output:
This is printed first
1
This is printed second
2
This is printed at last
3
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset