A generator is a piece of code that produces values one at a time, only when you ask for the next one. Instead of building a complete list up front, it pauses after each value and picks up where it left off on the next request. This makes it ideal for large or never-ending sequences.

Think of a ticket dispenser at a busy counter. It does not print every ticket for the day in advance; it hands out the next number the moment someone presses the button. A generator works the same way: it remembers its place and produces the following value on demand. Compare that to an array, which holds every item in memory at the same time, which is fine for small sets but wasteful for huge ones.

In a language like Python or modern JavaScript, a generator uses a keyword such as ‘yield’ to mark where it pauses. This lets a program read a multi-gigabyte file or stream live data line by line, using almost no memory no matter how big the source gets.

A common scenario is reading a giant CSV export. Load it as a normal list and the program might crash on a 4GB file. Read it through a generator and it sips one row at a time, so memory stays flat whether the file is a thousand rows or ten million. The trade-off is that you can only walk through it once, in order, and you cannot jump to item number 500 without passing the first 499. When you genuinely need random access or a fixed length, a plain list is the better tool.

At TopDevs we use generators when a client’s job has to chew through far more data than fits in memory, so the system stays fast and stable instead of grinding to a halt.