Last Updated : 29 Jul, 2025
A generator function is a special type of function that returns an iterator object. Instead of using return to send back a single value, generator functions use yield to produce a series of results over time. This allows the function to generate values and pause its execution after each yield, maintaining its state between iterations.
Example:
Python
def fun(max):
cnt = 1
while cnt <= max:
yield cnt
cnt += 1
ctr = fun(5)
for n in ctr:
print(n)
Explanation: This generator function fun yields numbers from 1 up to a specified max. Each call to next() on the generator object resumes execution right after the yield statement, where it last left off.
Why Do We Need Generators?Let's take a deep dive in python generators:
Creating GeneratorsCreating a generator in Python is as simple as defining a function with at least one yield statement. When called, this function doesn’t return a single value; instead, it returns a generator object that supports the iterator protocol. The generator has the following syntax in Python:
def generator_function_name(parameters):
# Your code here
yield expression
# Additional code can follow
Example: we will create a simple generator that will yield three integers. Then we will print these integers by using Python for loop.
Python
def fun():
yield 1
yield 2
yield 3
# Driver code to check above generator function
for val in fun():
print(val)
Yield vs Return
Example with return:
Python
def fun():
return 1 + 2 + 3
res = fun()
print(res)
Generator Expression
Generator expressions are a concise way to create generators. They are similar to list comprehensions but use parentheses instead of square brackets and are more memory efficient.
Syntax:
(expression for item in iterable)
Example: We will create a generator object that will print the squares of integers between the range of 1 to 6 (exclusive).
Python
sq = (x*x for x in range(1, 6))
for i in sq:
print(i)
Applications of Generators in Python
Suppose we need to create a stream of Fibonacci numbers. Using a generator makes this easy, you just call next() to get the next number without worrying about the stream ending.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4