How to Create Infinite Generator in Python Easily
To create an infinite generator in Python, define a function with
yield inside an endless loop like while True. This function will keep producing values one by one without stopping until you manually stop the iteration.Syntax
An infinite generator uses a function with a while True loop and yield to produce values endlessly.
def: defines the generator function.while True: creates an infinite loop.yield: produces a value each time the generator is asked for the next item.
python
def infinite_generator(): while True: yield None # replace None with what you want to generate
Example
This example creates an infinite generator that counts up from 1 endlessly. It shows how to get values one by one using next().
python
def count_up(): num = 1 while True: yield num num += 1 counter = count_up() print(next(counter)) # Output: 1 print(next(counter)) # Output: 2 print(next(counter)) # Output: 3
Output
1
2
3
Common Pitfalls
Common mistakes include:
- Forgetting
yieldand usingreturninstead, which stops the generator immediately. - Not using an infinite loop like
while True, so the generator stops after some values. - Not handling the infinite nature properly, which can cause your program to hang if you try to iterate without limits.
python
def wrong_generator(): return 1 # This returns once and stops, not a generator def correct_generator(): num = 1 while True: yield num num += 1
Quick Reference
Tips for infinite generators:
- Use
while Truefor endless loops. - Use
yieldto produce values one at a time. - Control iteration externally to avoid infinite loops in your program.
Key Takeaways
Use a function with while True and yield to create an infinite generator.
Never use return inside the generator if you want it to be infinite.
Always control how many items you take from the generator to avoid infinite loops.
You can get values one by one using next() on the generator object.
Infinite generators are useful for continuous data streams or counters.