Iterators & Generators In JavaScript, you already use iterators whenever you loop over arrays, strings, or use . Python also has a strong iterator protocol , and on top of that, it introduces generators — a simple way to create custom iterators using the keyword. These are especially useful when working with large datasets or streams, where you don’t want to load everything into memory at once. What is a Generator? A normal function runs top to bottom and returns one final value . A generator function can pause ( ) and resume later, returning values step by step. Think of it like this: Normal function = bucket of water → you get everything at once. Generator function = water tap → you get water little by little, only when you open the tap. How does work? When you call a generator function, it doesn’t execute immediately. Instead, it gives you a generator object . Each time you ask for the next value (using or looping), Python runs the function until the next . At that point: The function pauses . It remembers all its local variables, file handles, and the exact position where it stopped. The next call resumes right after the last , without restarting the whole function. Example – Reading a File in Chunks How it works step by step: 1. → creates a generator object. File not read yet. 2. First iteration: Opens the file. Reads first 1KB. sends that chunk out and pauses . 3. Next iteration: Resumes right after . Reads next 1KB. again, then pause. 4. Continues until file ends, then exits and closes the file. 👉 The file is opened only once , and the generator remembers the current file position between s. JS doesn’t have inside normal functions, but it has generator functions ( ) which work the same way. Example – Inventory Restock Simulation Output: ✅ Why it matters : Iterators let you loop consistently over any collection. Generators let you process large or infinite data step by step without memory blowups. Perfect for: file readers, log processors, streaming APIs, or simulations.