Python Iterators
An iterator is an object in Python used to iterate over iterable objects like lists, tuples, strings, etc. It implements two special methods:
__iter__()
__next__()
What Is an Iterable?
An iterable is any Python object capable of returning its members one at a time. Common examples:
my_list = [1, 2, 3]
my_str = "hello"
You can convert them into iterators using iter()
.
Example 1: Creating an Iterator from a List
my_list = [10, 20, 30]
my_iter = iter(my_list)
print(next(my_iter)) # 10
print(next(my_iter)) # 20
print(next(my_iter)) # 30
Output:
10
20
30
If you call next()
again, it will raise StopIteration
.
Custom Iterator Example
You can create your own iterator by defining a class with __iter__()
and __next__()
methods.
class CountUpTo:
def __init__(self, max):
self.max = max
self.current = 1
def __iter__(self):
return self
def __next__(self):
if self.current <= self.max:
val = self.current
self.current += 1
return val
else:
raise StopIteration
counter = CountUpTo(3)
for num in counter:
print(num)
Output:
1
2
3
Iterator vs Iterable
Term | Method Required | Example Objects |
---|---|---|
Iterable | __iter__() | list, tuple, dict, set |
Iterator | __next__() & __iter__() | object from iter() call |
Using iter()
and next()
nums = [1, 2, 3]
it = iter(nums)
print(next(it)) # 1
print(next(it)) # 2
print(next(it)) # 3
Summary
- Iterables can be looped through.
- Iterators are used to get items from iterables one by one using
next()
. - Iterators remember their state.
- You can build custom iterators using
__iter__()
and__next__()
.