0
0
PythonConceptBeginner · 3 min read

What is Generator in Python: Simple Explanation and Example

A 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.

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
🎯

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 yield to 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.

Key Takeaways

Generators produce values on demand using the yield keyword.
They save memory by not creating all values at once.
Use generators for large data or infinite sequences.
Generators can be iterated like lists but are more efficient.