# Generator (Programming)

> A function that pauses at each yield and hands out one value at a time.

**Field:** Software Development  
**Category:** Programming Paradigms  
**Also known as:** Generator Function, yield, Generators

## Think of it like

It is like a cook who makes one pancake each time you ask. No big stack waits on the side.

## Definition

A generator is a function that hands out values one at a time with the word yield. Each time it yields, it pauses and keeps its place. When the next value is asked for, it carries on from there. Python uses yield in a normal def. JavaScript marks a generator with function*. A generator is a quick way to make an iterator.

## Example

Emma needs a million ticket numbers. A generator makes each one only when asked. So they never all sit in memory at once.

## Example code

```python
def count_to(n):
    i = 1
    while i <= n:
        yield i
        i += 1

print(list(count_to(3)))
# [1, 2, 3]
```

yield hands out one number, pauses, then goes on when asked again.

## Why it matters

It saves memory, because values are made only when needed. It can even describe a list with no end.

## Common mistake

Thinking the body runs when you call a generator. The call only makes it. The code runs as you ask for each value.

## Three principles

- **yield.** Hands out a value and pauses.
- **Lazy.** Makes each value only when asked.
- **An easy iterator.** Less code than writing one by hand.

## Related terms

- [Iterator](https://learn.benibix.com/term/development/iterator)
- [Function](https://learn.benibix.com/term/development/function)
- [Loop](https://learn.benibix.com/term/development/loop)
- [Async/Await](https://learn.benibix.com/term/development/async-await)
- [Memory Management](https://learn.benibix.com/term/development/memory-management)

## Told apart from

- [Iterator vs Generator](https://learn.benibix.com/compare/iterator-vs-generator): An iterator is any object that gives items one at a time. A generator is a short way to write one: a function that pauses at each yield.

![Two panels. On the left, an iterator: a list of three fruits with a pointer that moves one step on each call to next, and stops after the last. On the right, a generator: a function with a yield line hands out 1, then pauses, then 2, then 3, making each value only when asked.](https://learn.benibix.com/diagrams/dev7-iterator-generator.svg)

---

Source: https://learn.benibix.com/term/development/generator
Author: Behnia Zarei (a developer in Vienna, Austria, who builds and teaches data, AI and business intelligence at BENIBIX)
Publisher: BENIBIX Learn (https://learn.benibix.com/)
Last updated: 2026-11-17
Licence: CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Quote freely with attribution.
