If you have some confusion when you check if an object is iterable in Python, read our article carefully to get the answer.
Methods To Check If An Object Is Iterable
An iterable object is an object which has the capability of returning its elements, especially in for loop.
n = 5 # TypeError: 'int' object is not iterable for i in n: print(f"i = {i}")
Let’s follow some methods below to check if an object is iterable in Python.
Check if object has __iter__ protocol by using hasattr() function
Any iterable objects have the __iter__() method to represent its character. Now, we use the hasattr() function, which is used to check if an object has a particular attribute and if __iter__() is a part of the object.
Code:
myList = ["sun", "star", "moon", "sky"] number = 22 if hasattr(myList, "__iter__"): print(f'{myList} is iterable') else: print(f'{myList} is iterable') if hasattr(number, "__iter__"): print(f'{number} is iterable') else: print(f'{number} is not iterable')
Result:
['sun', 'star', 'moon', 'sky'] is iterable
22 is not iterable
Check by “class collections.abc.Iterable”
Collections.abc.Iterable class provides a reliable way to check if the object is an instance of the class or has __iter__() method. We will use the isinstance() function to test if the object is iterable.
Code:
from collections.abc import Iterable myList = ["sun", "star", "moon", "sky"] number = 22 if isinstance(myList, Iterable): print(f"{myList} is iterable") else: print(f"{myList} is iterable") if isinstance(number, Iterable): print(f"{number} is iterable") else: print(f"{number} is not iterable")
Result:
['sun', 'star', 'moon', 'sky'] is iterable
22 is not iterable
Method 3: Using the built-in iter() function
When passing an iterable object to iter(), it will return an iterator for the object. So, we only need to check if the object type is the iterator.
Code:
myList = ["sun", "star", "moon", "sky"] number = 22 if type(iter(myList)): print(type(iter(myList))) else: print(f"{myList} is not iterable") try: iter(number) print(type(iter(number))) except TypeError: print(f"{number} is not iterable")
Result:
<class 'list_iterator'>
22 is not iterable
Summary
In short, an iterable object is any object you can use as a loop to traverse through all elements. But you can also test the object with our methods above to check if an object is iterable in Python.
Maybe you are interested:
- Split a string every nth character in Python
- Split a string by whitespace in python
- Split a string with multiple delimiters in python

My name is Robert Collier. I graduated in IT at HUST university. My interest is learning programming languages; my strengths are Python, C, C++, and Machine Learning/Deep Learning/NLP. I will share all the knowledge I have through my articles. Hope you like them.
Name of the university: HUST
Major: IT
Programming Languages: Python, C, C++, Machine Learning/Deep Learning/NLP