🧭Iterator
Also known as Iterators, Iterable, Iterator Protocol
An object that hands out items one at a time, each time you ask.
Think of it like
It is like a bookmark in a book. It always knows which page comes next.
Example
Jack reads a huge log file line by line with an iterator. Only one line is in memory at a time.
Why it matters
It lets one loop work over many kinds of collection. It also lets you walk through data too big to load at once.
Definition
Example code
python
it = iter(["apple", "pear"])
print(next(it)) # apple
print(next(it)) # pear
next(it) # StopIterationCommon mistake
Key takeaways
- 1One at a time. Each call gives the next item.
- 2Knows its place. It remembers where it stopped.
- 3Runs out. Most cannot be rewound.