Sometimes, we want to determine if an object is iterable in Python.
In this article, we’ll look at how to determine if an object is iterable in Python.
How to determine if an object is iterable in Python?
To determine if an object is iterable in Python, we can use the collections
module.
For instance, we write:
from collections.abc import Iterable
x = 100
y = [1, 2]
x_iterable = isinstance(x, Iterable)
y_iterable = isinstance(y, Iterable)
print(x_iterable)
print(y_iterable)
We import Iterable
from the collections.abc
module.
Then we call isinstance
with the variables we want to check and Iterable
to check if x
and y
are iterable.
Therefore, x_iterable
is False
and y_iterable
is True
since x
is an integer and y
is an array.
Conclusion
To determine if an object is iterable in Python, we can use the collections
module.