Python Iterators
Python · Functions & OOP
Theory
An iterator is an object that produces values one at a time and remembers where it is. It follows the iterator protocol: __iter__() returns the iterator itself and __next__() returns the next value, raising StopIteration when nothing is left. An iterable (a list, string, dict, file) is anything you can call iter() on to get a fresh iterator.
A for loop is built on this: for x in [1, 2, 3] calls iter() on the list, then keeps calling next() until StopIteration ends the loop quietly. Iterators are lazy - they compute or fetch each value only when asked - so you can walk through a huge file line by line without loading it all into memory. A generator function that uses yield is the easiest way to write your own iterator.
Why we use it
Iterators give one uniform way to loop over any kind of collection or stream, and because they are lazy they handle very large or even endless data using very little memory.
When to use it
Use iterators and generators to stream large files, database rows or computed sequences. Once consumed, an iterator is exhausted; if you need to reuse values or index them, convert to a list with list(it).
How it works
- it = iter([1, 2, 3])
- Call next(it)
- Any items left? Yes: Return the next item and move the position forward. No: Raise StopIteration.
- Repeat next(it) as needed
- A for loop catches StopIteration and stops
Syntax
iter(obj)
next(iterator)Example
it = iter([1,2,3])
next(it) # 1Key points
- for loops use iterators internally
- Generators (functions with yield) are a simple way to build iterators
- An iterator is single-use: once exhausted it stays empty
- next(it, default) returns default instead of raising StopIteration
- Lists are iterables, not iterators - iter(list) gives the iterator