How to check if an object is iterable in Python?

Boaz picture Boaz · Jan 12, 2011 · Viewed 42k times · Source

How does one check if a Python object supports iteration, a.k.a an iterable object (see definition

Ideally I would like function similar to isiterable(p_object) returning True or False (modelled after isinstance(p_object, type)).

Answer

user225312 picture user225312 · Jan 12, 2011

You can check for this using isinstance and collections.Iterable

>>> from collections.abc import Iterable # for python >= 3.6
>>> l = [1, 2, 3, 4]
>>> isinstance(l, Iterable)
True

Note: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated since Python 3.3, and in 3.9 it will stop working.