In Python, how do I determine if an object is iterable?
In Python, an object is considered iterable if it has an __iter__() method defined or if it has a __getitem__() method with defined indices (i.e., it can be indexed, like a list or a string).
In Python, an object is considered iterable if it has an __iter__() method defined or if it has a __getitem__() method with defined indices (i.e., it can be indexed, like a list or a string).
The built-in iter() function can be used to check if an object is iterable. If the object is iterable, iter() returns an iterator object; otherwise, it raises a TypeError. For example:
Determine if an object is iterable with a try-except block in Python
def is_iterable(obj):
try:
iter(obj)
return True
except TypeError:
return False
print(is_iterable(2))
<div class="alert alert-info flex not-prose">![]()
<span class="hidden md:block">Watch a video course</span>Python - The Practical Guide</div>
You can also use collections.abc.Iterable ABC and check using the isinstance function.
A function that determines if an object is iterable using the iterable module in Python
from collections.abc import Iterable
def is_iterable(obj):
return isinstance(obj, Iterable)You can then use this function to check if any object is iterable or not.
Determines if an object is iterable using the iterable module in Python with examples
from collections.abc import Iterable
def is_iterable(obj):
return isinstance(obj, Iterable)
is_iterable([1, 2, 3])
is_iterable('abc')
is_iterable(5)Note that isinstance(obj, Iterable) relies on Python's protocol-based duck-typing, meaning it checks for the presence of the __iter__() method rather than strict inheritance. This avoids false negatives for custom classes that implement the iterable protocol without inheriting from collections.abc.Iterable. For sequence-like objects that rely on __getitem__() instead, you can also verify iterability with hasattr(obj, '__getitem__').