Codele / Advanced programming
Iterators and generators
Sometimes you want items one at a time, only when you ask, without making the whole list first. Think of a ticket dispenser that prints a ticket when you pull the lever.
- An iterator hands out items one at a time. Each time you ask “next?”, you get the next item, and it remembers where it was.
- A generator is a function that makes an iterator for you: it runs until yield, hands out a value and pauses, keeping its variables until it is asked again.
- Nothing runs until the first ask, and later squares are never made if you stop early. That is why a generator can describe an endless sequence, or a huge file, in very little memory.
- Python (yield), JavaScript (function) and C# (yield return) have generators built in. Java, C++ and Go do not, so you write an iterator object with a next method, or in Go a closure.
Loading the playable lesson…