Generator Function in Python

A generator function in Python is defined like a normal function, but whenever it needs to generate a value, it does so with the yield keyword rather than return. If the body of a def contains yield, the function automatically becomes a Python generator function. 

Create a Generator in Python

In Python, we can create a generator function by simply using the def keyword and the yield keyword. The generator has the following syntax in Python:

def function_name():
yield statement

Example:

In this example, we will create a simple generator that will yield three integers. Then we will print these integers by using Python for loop.

Python3




# 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)


Output:

1
2
3

Generators in Python

A Generator in Python is a function that returns an iterator using the Yield keyword. In this article, we will discuss how the generator function works in Python.

Similar Reads

Generator Function in Python

A generator function in Python is defined like a normal function, but whenever it needs to generate a value, it does so with the yield keyword rather than return. If the body of a def contains yield, the function automatically becomes a Python generator function....

Generator Object

...

Python Generator Expression

Python Generator functions return a generator object that is iterable, i.e., can be used as an Iterator. Generator objects are used either by calling the next method of the generator object or using the generator object in a “for in” loop....