single
Generator Functions
Swipe to show menu
A generator function is a special type of function that uses the yield keyword instead of return to generate a sequence of values. When a generator function is called, it returns an iterator object, which can be iterated over to retrieve values one at a time.
The main advantage of generator functions is their memory efficiency. Instead of generating the entire sequence upfront and storing it in memory, generators produce values on-the-fly as they are needed.
How yield Works
Unlike return, which exits the function entirely, yield pauses the function and saves its state. The next time next() is called, the generator resumes from exactly where it left off:
12345678910def count_up(start, stop): while start <= stop: yield start # Pause and return the current value start += 1 # Resume from here on the next call counter = count_up(1, 3) print(next(counter)) # 1 print(next(counter)) # 2 print(next(counter)) # 3
You can also iterate over a generator using a for loop – it automatically calls next() until the generator is exhausted:
1234567def count_up(start, stop): while start <= stop: yield start start += 1 for value in count_up(1, 5): print(value) # 1, 2, 3, 4, 5
Once a generator is exhausted (no more values to yield), calling next() on it will raise a StopIteration error. A for loop handles this automatically.
Swipe to start coding
Implement a even_numbers generator function that yields even numbers in a given range.
- Define a generator function
even_numbersthat takes two parameters:startandstop. - Use a
whileloop to iterate whilestartis less than or equal tostop. - Use
yieldto returnstartonly if it is even (divisible by 2). - Increment
startby 1 after each iteration. - Use a
forloop to print all generated values.
Solution
Thanks for your feedback!
single
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat