Home›Community›What are Python generators and when should you use them?
What are Python generators and when should you use them?
Coding Now Expert •
Jun 13, 2026 •
136 views
A generator is a function that yields values one at a time instead of returning them all at once — saving memory.
**Regular function vs Generator:**
```python
# Regular function — loads ALL data into memory
def get_squares(n):
return [x**2 for x in range(n)]
# Generator — produces one value at a time
def gen_squares(n):
for x in range(n):
yield x**2
# Usage
for sq in gen_squares(1000000): # Uses almost no memory!
print(sq)
```
**When to use generators:**
1. Processing large files line by line
2. Infinite sequences (streaming data)
3. Pipeline processing (chain generators together)
4. Reading large DB result sets
**Generator expression (like list comprehension):**
```python
squares = (x**2 for x in range(1000000)) # Note: () not []
```
Generators are one of Python's most powerful features for data engineering.