Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Generator Functions | Function Return Value Specification
Python Functions Tutorial
Section 4. Chapter 4
single

single

bookGenerator Functions

Swipe to show menu

Note
Definition

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:

12345678910
def 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
copy

You can also iterate over a generator using a for loop – it automatically calls next() until the generator is exhausted:

1234567
def 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
copy
Note
Note

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.

Task

Swipe to start coding

Implement a even_numbers generator function that yields even numbers in a given range.

  1. Define a generator function even_numbers that takes two parameters: start and stop.
  2. Use a while loop to iterate while start is less than or equal to stop.
  3. Use yield to return start only if it is even (divisible by 2).
  4. Increment start by 1 after each iteration.
  5. Use a for loop to print all generated values.

Solution

Switch to desktopSwitch to desktop for real-world practiceContinue from where you are using one of the options below
Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 4. Chapter 4
single

single

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

some-alt