Generators1 / 4
CRASH COURSE
Generators
A function containing yield becomes a generator. Calling it returns an iterator instead of running the whole body.
- Each time the loop asks for the next value, the function resumes after the previous yield. Values are produced lazily, so memory stays small.
- A generator can be used once. Create a new one to start again.
def count_up(limit):
n = 1
while n <= limit:
yield n
n += 1
for value in count_up(3):
print(value)