Python Iterators
An iterator is an object that lets you traverse through a sequence of values one element at a time. Instead of holding all values in memory at once, an iterator produces values on demand.
In Python, an iterator follows the iterator protocol, which means it implements two special methods:
-
__iter__()→ returns the iterator object -
__next__()→ returns the next value from the sequence
Iterator vs Iterable
- Iterable: An object you can loop over (list, tuple, string, set, dictionary, etc.)
- Iterator: The object that actually keeps track of iteration and returns values one by one
You can get an iterator from any iterable using the built-in
iter() function.
Getting an Iterator from an Iterable
Example: Iterator from a List
Example: Iterator from a String
Strings are also iterable, character by character.
Looping Through an Iterator
You usually don’t call next() manually. A for loop
does this automatically behind the scenes.
Example: Looping Through a Set
Example: Looping Through a String
Note: Internally, the for loop:
-
Creates an iterator using
iter() - Calls
next()repeatedly -
Stops when
StopIterationis raised
Creating Your Own Iterator
To create a custom iterator, define a class that implements:
__iter__()__next__()
Example: Custom Iterator (Even Numbers)
This iterator generates even numbers starting from 2.
Preventing Infinite Iteration – StopIteration
Without a stopping condition, an iterator can run forever. To stop
iteration, raise the StopIteration exception inside
__next__().
Example: Iterator with a Stop Condition
This iterator generates square numbers up to a limit.
