Iterator
PronunciationIT-er-ay-ter
Definition
An iterator is an object that produces the items of a sequence one at a time. Each request gives the next item, and when nothing is left it signals the end.
Where you hear it
When people explain how for loops work, in discussions of generators, and when a loop mysteriously runs only once.
Examples
Calling
next()on the iterator returns the next item.The iterator is exhausted, so the second loop prints nothing.
Once the iterator is used up, a new loop needs a fresh iterator.
Common mistake
Looping over the same iterator twice. Once it is used up it stays empty; create a new one or keep the data in a list.
Don't confuse with
An iterable, which is the thing you loop over. Asking an iterable for an iterator is what a for loop does first.
Say it at work
- In a meeting or chat
That's an iterator, so you can only consume it once.
- In an email or ticket
Wrap it in
list()if you need to read it twice.
Keep exploring
More in Programming Fundamentals