How to Check Whether an Object is Iterable in Python 3

In Python, an iterable object is any object capable of returning its members one at a time, permitting it to be iterated over in a loop. For example, string and list are iterable.
This short post shows you two different ways to check if a given object is iterable in Python 3.
Using Duck Test (see Duck Typing – Wikipedia)
Example:
# Create a function for reusable purpose
def is_iterable(object):
try:
iter(object)
return True
except TypeError:
return False
# Use the function
a = 'KindaCode.com'
print(is_iterable(a))
b = 1234
print(is_iterable(b))
c = {
"k1": 10,
"k2": 3,
"k3": 9
}
print(is_iterable(c))
Output:
True
False
True
Using the instance function (not recommended)
Example:
from collections.abc import Iterable
a = 'KindaCode.com'
print(isinstance(a, Iterable))
b = [1, 2, 3]
print(isinstance(b, Iterable))
Output:
True
True
Further reading:
- Examples of using map() function in Python 3
- Examples of using Lambda Functions in Python 3
- Using the isinstance() function in Python 3
- How to Install Python Libraries in Google Colab
- Extract all links from a webpage using Python and Beautiful Soup 4
You can also check out our Machine Learning category page or Python category page for more tutorials and examples.
Subscribe
0 Comments