Python Iterators
An iterator is an object that represents a stream of data and returns one element at a time when you call next() on it. Lists, tuples, sets, dictionaries, and strings are iterables — objects from which you can obtain an iterator using iter().
1. Using iter() and next()
Call iter() on an iterable to get an iterator, then call next() to step through its elements one by one:
languages = ["Python", "Java", "PHP"]
it = iter(languages)
print(next(it)) # Output: Python
print(next(it)) # Output: Java
print(next(it)) # Output: PHP
2. How for Loops & StopIteration Work
Behind the scenes, a for loop calls iter() on the collection and repeatedly calls next() until a StopIteration exception is raised, which it catches automatically:
nums = (10, 20)
it = iter(nums)
while True:
try:
print(next(it))
except StopIteration:
break
3. Creating a Custom Iterator Class
To build your own iterator class, implement both __iter__() (returning the iterator object itself) and __next__() (returning the next value or raising StopIteration):
class CountDown:
def __init__(self, start):
self.current = start
def __iter__(self):
return self
def __next__(self):
if self.current <= 0:
raise StopIteration
value = self.current
self.current -= 1
return value
for n in CountDown(3):
print(n) # Output: 3, 2, 1
Tip: Iterators remember their current position and are consumed as you iterate through them — call
iter() again on an iterable whenever you need a fresh pass.