This Python Generators lesson is for a beginner. Read the short notes, run each example, then change one name or number and run it again.
A generator uses yield instead of return. Each request resumes just after the last yield, with the local variables still in place.
list() pulls every yielded value. Use a generator when you do not want the full list built first.
Example 1: Start here
yield pauses the function. n is still there on the next request.
def seats(limit): # define the function; it runs when you call it
n = 1 # a whole number
while n <= limit: # keep repeating while this stays true
yield n # pause here and hand a value back
n += 1 # update the stored value
print(list(seats(3)))
Example 2: Yield one at a time
yield pauses the function and hands back one value.
def counts(): # define the function; it runs when you call it
yield 1 # pause here and hand a value back
yield 2 # pause here and hand a value back
yield 3 # pause here and hand a value back
print(list(counts()))
Example 3: A generator expression
The parentheses build a generator. list pulls every value out of it.
scores = [60, 82, 91] # a list; the values stay in this order
passed = (score for score in scores if score >= 80) # a tuple; a fixed group of values
print(list(passed))
Example 4: Stop early
You do not have to consume every yielded value.
def counts(): # define the function; it runs when you call it
for n in range(1, 10): # repeat once per number; range stops before the last
yield n # pause here and hand a value back
for n in counts(): # repeat the indented lines once per value
if n == 3: # run the indented lines only when this is true
break # leave the loop now
print(n)
