Generator Function

Last Updated: 02th September 2025


A generator function is a function that returns an iterator object, which can be used to iterate over a sequence of values. Generator functions are useful when you want to create a sequence of values that can be generated on demand, rather than all at once.

Syntax:

def generator_function():
    yield value1
    yield value2
    yield value3
  • yield keyword is used to generate a value and return it to the caller.

Example 1.

def my_gen():
    yield 1
    yield 2
    yield 3

for val in my_gen():
    print(val)
# Output: 1, 2, 3

Example 2.

# Using Next
def simple_gen():
    yield "A"
    yield "B"

g = simple_gen()
print(next(g))  # A
print(next(g))  # B
  • next(g) is a built-in function that returns the next value from the iterator object g.

Example 3.

# generator expression
nums = (x * 2 for x in range(5))
print(list(nums))  # [0, 2, 4, 6, 8]

Example 4.

# itter() - to convert iterable to iterator
nums = [1, 2, 3, 4, 5]
it = iter(nums)
print(next(it))  # 1
print(next(it))  # 2