![]() |
VOOZH | about |
In simple words, any object that could be looped over is iterable. For instance, a list object is iterable and so is an str object. The list numbers and string names are iterables because we are able to loop over them (using a for-loop in this case). In this article, we are going to see how to check if an object is iterable in Python.
Examples:
Input: "Hello"
Output: object is not iterable
Explanation: Object could be like( h, e, l, l, o)
Input: 5
Output: 'int' object is not iterable
Example 1:
Output:
H e l l o
Example 2:
Output
TypeError: 'int' object is not iterable
However, an int object is not iterable and so is a float object. The integer object number is not iterable, as we are not able to loop over it.
We are going to explore the different ways of checking whether an object is iterable or not. We use the hasattr() function to test whether the string object name has __iter__ attribute for checking iterability. However, this check is not comprehensive.
Output:
Roster is iterable
We could verify that an object is iterable by checking whether it is an instance of the Iterable class. The instance check reports the string object as iterable correctly using the Iterable class. This works for Python 3 as well. For Python 3.3 and above, you will have to import the Iterable class from collections.abc and not from collections like so:
Output:
Roster is iterable
The iter built-in function works in the following way:
Code:
Output:
Roster is iterable
Here we will check the type of object is iterable or not.
Output:
not iterable