Python Iterable
What Is an Iterable?
An iterable is any Python object capable of returning its members one at a time, allowing it to be looped over in a for loop. Common iterables include lists, tuples, strings, dictionaries, sets, and custom objects that implement the iteration protocol.
The collections.abc.Iterable
abstract base class (ABC) defines the minimal interface for iterable types: the presence of the __iter__()
method.
The iter Method
To be recognized as an iterable, a class must implement the __iter__(self)
method, which should return an iterator (an object with a __next__()
method):
class MyIterable:
def __iter__(self):
return iter([1, 2, 3])
obj = MyIterable()
for item in obj:
print(item) # 1, 2, 3
Using collections.abc.Iterable
You can check if a class or object is iterable using isinstance
or issubclass
:
from collections.abc import Iterable
print(isinstance([1, 2, 3], Iterable)) # True (list is iterable)
print(isinstance(42, Iterable)) # False (int is not iterable)
Why Use Iterable?
- To make your custom classes compatible with for loops and other iteration contexts.
- To use type checking and static analysis tools that recognize the Iterable ABC.
- To clarify intent in your code and documentation.
Concrete Example: Custom Iterable Class
Suppose you want to create a class that counts down from a given number to 1. You can make it iterable by implementing __iter__()
:
from collections.abc import Iterable
class Countdown(Iterable):
def __init__(self, start):
self.start = start
def __iter__(self):
n = self.start
while n > 0:
yield n
n -= 1
for number in Countdown(3):
print(number)
# Output:
# 3
# 2
# 1
- This allows you to use your custom class in a for loop or any context that expects an iterable.
Summary
collections.abc.Iterable
is the base class for objects that can be looped over.- Requires the
__iter__()
method. - Used for type checking and to build custom iterable types.