Core Python
June 3, 2026 1 min read

Mastering Python Generators: Simplify Iteration and Save Memory

HS
HEMANT SINGH
Technical Writer & Educator

Generator is a simple way to create iterators, it is also called a function which return an object

 

Generator function

A function that contains a yield statement is called generator function

 

def squares(length):
	for n in range(length):
		yield n**2

 

for square in squares(5):
	print(square)

Python generator expression

A generator express return generator object.

 

cubes = (n*n*n for n in range(5))
for cube in cubes:
	print(cube)