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).
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:
def is_iterable(obj):
try:
iter(obj)
return True
except TypeError:
return False
print(is_iterable(2))
Watch a video course
Python - The Practical Guide
You can also use collections.abc.Iterable
ABC and check using the issubclass
function.
from collections.abc import Iterable
def is_iterable(obj):
return issubclass(type(obj), Iterable)
You can then use this function to check if any object is iterable or not.
from collections.abc import Iterable
def is_iterable(obj):
return issubclass(type(obj), Iterable)
is_iterable([1, 2, 3])
is_iterable('abc')
is_iterable(5)
It's worth noting that any class that is not a string, dict, or other fundamental type and which is defined by you or someone else will be considered iterable by this method because it could define the iter method.