How to Check if an Object is Iterable in Python
Determining whether an object is iterable (can be used in a loop) is a fundamental task in Python.
This guide explains the most reliable method for checking iterability using the iter()
function and try-except
blocks. It also discusses why alternative approaches (like checking for __iter__
or using collections.abc.Iterable
) are less comprehensive.
Checking for Iterability with iter()
(Recommended)
The most reliable and Pythonic way to check if an object is iterable is to use the built-in iter()
function within a try-except
block:
my_str = 'hello'
try:
my_iterator = iter(my_str) # Attempt to get an iterator
print('The object is iterable')
for i in my_iterator: # We can iterate over the object
print(i) # Output: h, e, l, l, o
except TypeError as te:
print('The object is NOT iterable')
print(te)
iter(my_str)
attempts to get an iterator from the object.- If the object is not iterable, then
iter()
will raise aTypeError
exception. - If the
try
block succeeds (noTypeError
), the object is iterable.
Creating a Reusable Function
For convenience, encapsulate this logic in a reusable function:
def is_iterable(value):
try:
iter(value)
return True
except TypeError:
return False
print(is_iterable('hello')) # Output: True
print(is_iterable(100)) # Output: False
- This function can be used for checking any variable if its type is iterable or not.
Why collections.abc.Iterable
is Insufficient
You might encounter code that uses collections.abc.Iterable
and isinstance()
:
from collections.abc import Iterable
my_list = ['a', 'b', 'c']
print(isinstance(my_list, Iterable)) # Output: True
print(isinstance(100, Iterable)) # Output: False
However, this approach is not comprehensive. It only checks if the object's class (or a parent class) is registered as a subclass of Iterable
. It doesn't detect objects that are iterable via the __getitem__
method (the sequence protocol), which is a valid way to make an object iterable. Therefore, relying solely on isinstance(obj, Iterable)
can lead to false negatives.
iter()
is the most reliable method because it checks for both __iter__()
and __getitem__()
(the sequence protocol).
Most Iterable Built-in Objects Implement the __iter__
Method
Most built-in iterable objects implement the __iter__()
method, making it possible to check for iterability using iter()
method. Here are a few examples of Python built-in objects that implement the __iter__
method:
print({}.__iter__)
print(().__iter__)
print([].__iter__)
print(''.__iter__)
print({'a', }.__iter__)
Making a Class Iterable
To make your own classes iterable, you need to implement either __iter__()
(returning an iterator) or __getitem__
(for sequence-like behavior). The more common and flexible approach is to use __iter__()
:
class Counter:
def __init__(self, start, stop):
self.current = start - 1
self.stop = stop
def __iter__(self):
return self # Return iterator
def __next__(self):
self.current += 1
if self.current < self.stop:
return self.current
raise StopIteration # Indicate the iteration is over
for c in Counter(0, 4):
print(c) # Output: 0, 1, 2, 3
- This
Counter
class is iterable because it defines both__iter__
and__next__
.