How to Create Generator in Python: Simple Guide with Examples
In Python, you create a generator by defining a function that uses the
yield keyword instead of return. This makes the function return an iterator that produces values one at a time, saving memory and allowing lazy evaluation.Syntax
A generator function looks like a normal function but uses yield to produce a sequence of values. Each time yield is called, the function pauses and returns a value, resuming from there on the next call.
def: defines the generator function.yield: pauses and sends a value back to the caller.- Function returns a generator object, which is an iterator.
python
def generator_function(): value = 1 # example value yield value # produces a value and pauses # more code or yields can follow
Example
This example shows a generator that yields numbers from 1 to 3. It demonstrates how the generator pauses after each yield and resumes when next value is requested.
python
def count_up_to_three(): yield 1 yield 2 yield 3 for number in count_up_to_three(): print(number)
Output
1
2
3
Common Pitfalls
Common mistakes include using return instead of yield, which ends the function and does not create a generator. Another is forgetting that generators can only be iterated once.
Also, trying to access generator values by index like a list will not work because generators produce values on demand.
python
def wrong_generator(): return 1 # This ends the function immediately, no generator created def correct_generator(): yield 1 # This creates a generator # Using the generators print(type(wrong_generator())) # <class 'int'> print(type(correct_generator())) # <class 'generator'>
Output
<class 'int'>
<class 'generator'>
Quick Reference
- Use
yieldinside a function to create a generator. - Generators produce values lazily, saving memory.
- Use
forloops ornext()to get values from generators. - Generators can only be iterated once.
Key Takeaways
Use
yield in a function to create a generator that produces values one at a time.Generators save memory by generating values lazily instead of storing them all at once.
You can iterate over generators with
for loops or next() calls.Generators can only be used once; after exhaustion, they do not reset.
Avoid using
return when you want to create a generator; use yield instead.