What is Generator in Python: Simple Explanation and Example
generator in Python is a special type of function that returns an iterator which yields items one at a time, saving memory. Instead of returning all values at once, it produces them on demand using the yield keyword.How It Works
Think of a generator like a vending machine that gives you one snack at a time when you press a button, instead of handing you the whole box at once. When a generator function runs, it pauses at each yield statement, remembers where it left off, and waits until you ask for the next item.
This means it doesn't create and store all the values in memory upfront. Instead, it generates each value only when needed, which is very efficient for large data or streams.
Example
This example shows a generator function that yields numbers from 1 to 3 one by one.
def count_up_to_three(): yield 1 yield 2 yield 3 for number in count_up_to_three(): print(number)
When to Use
Use generators when you want to handle large data without using much memory, like reading big files line by line or generating infinite sequences. They are great for improving performance and reducing memory use in programs that process data streams or large collections.
For example, if you want to process millions of records one at a time, a generator helps you avoid loading all records into memory at once.
Key Points
- Generators use
yieldto produce values one at a time. - They save memory by not storing all values at once.
- Generators can be iterated over like lists but are more efficient.
- They pause and resume their state between yields.