
Definition: A generator in Python is a special kind of function that returns an iterator. Instead of using return
, it uses the yield
keyword to produce values one at a time, preserving its internal state between calls.
How a Generator Works
When a function contains yield
, calling it does not execute the function body immediately. Instead, it returns a generator object that can be iterated over with for
or next()
.
def count(limit):
for i in range(1, limit + 1):
yield i
# Create a generator object
gen = count(3)
print(gen) # <generator object count at 0x...>
print(next(gen)) # 1
print(next(gen)) # 2
print(next(gen)) # 3
# StopIteration when finished
Advantages of Generators
- Memory efficiency: they don’t build the entire sequence in memory, only one value at a time.
- Infinite streams: can generate values indefinitely (useful for sensors, data streams, or continuous calculations).
- Native integration: work naturally with
for
loops, comprehensions, and functions likesum()
,max()
, andany()
.
Practical Example
def squares(n):
for i in range(1, n + 1):
yield i ** 2
for value in squares(5):
print(value)
# 1, 4, 9, 16, 25
Infinite Generators
Generators can run indefinitely if no stop condition is included:
def infinite_counter():
n = 1
while True:
yield n
n += 1
for x in infinite_counter():
if x > 5:
break
print(x)
Comparison with Lists
Lists
store all elements in memory at once.Generators
compute each element on demand (lazy evaluation).
See Also
- Iterator (Python): an object returned by
iter()
or by a generator function. - Iterable (Python): an object capable of providing an iterator.
- Generator comprehension: compact syntax using parentheses to create a generator on the fly.