Understanding Python Generators and Generator Expressions
This article introduces Python generators, explains how the yield statement creates generator functions, demonstrates usage with example code, compares yield to return, and shows how generator expressions provide memory-efficient iteration similar to list comprehensions.
Python generators allow functions to produce a sequence of values lazily using the yield statement, which pauses execution and returns a value each time it is iterated.
The following example defines a simple countdown generator and shows how to retrieve values using the built-in next() function or by iterating with a for loop.
def countdown(n):
print("Counting down from %s" % n)
while n > 0:
yield n
n -= 1
return
c = countdown(10)
print(c.__next__()) # avoid calling the special method directly
print(next(c))
for i in c:
print(i, end=' ')Calling __next__() or next() advances the generator until it reaches a yield statement, at which point execution stops and the yielded value is returned. The generator can be closed with close() when no longer needed.
A modified generator can yield transformed values, as shown in the countdown1 example, where each yielded number is squared.
def countdown1(n):
print("Counting down from %s" % n)
while n > 0:
yield n*n
n -= 1
return
c = countdown1(10)
print(next(c))
print(next(c))
print(next(c))
for i in c:
print(i, end=' ')While yield and return both produce output, yield creates a generator that can produce multiple values over time, whereas return terminates the function after a single value.
Generator expressions provide a concise way to create generators similar to list comprehensions, using parentheses instead of brackets. They are memory-efficient because they generate items on-the-fly, which is useful for processing large data streams.
print('')
print("生成器表达式:")
b = (x*x for x in range(10) if (x % 2 == 0))
print(next(b))
print(next(b))
for i in b:
print(i, end=' ')Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.