A generator in Python is a special type of function that returns an iterable sequence of values - meaning it produces items one at a time, only when requested, rather than computing them all at once and saving them in memory.
Instead of using a
returnstatement, generators use theyieldkeyword. When the generator function is called, it does not actually run the code; it returns a generator object.Every time we call
next()on it, it runs until it hitsyield, pauses right there, remembers its entire state, and outputs the value.Feature
Normal Function (return)
Generator Function (yield)
Execution
Runs completely from start to finish.
Pauses and resumes its state at every
yield.Memory Output
Creates the entire list in memory instantly.
Generates one item at a time on the fly.
# A normal function creates the whole list in memory
def get_numbers_list(n):
result = []
for i in range(n):
result.append(i)
return result
# A generator yields one item at a time
def get_numbers_gen(n):
for i in range(n):
yield i