How to Check Whether an Object is Iterable in Python 3

Last updated on November 3, 2021 Pennywise Loading... Post a comment

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:

You can also check out our Machine Learning category page or Python category page for more tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

You May Also Like