In Python, how do I determine if an object is iterable?


Is there a method like isiterable? The only solution I have found so far is to call

hasattr(myObj, '__iter__')

But I am not sure how fool-proof this is.

11/12/2013 1:38:23 AM

Accepted Answer

  1. Checking for __iter__ works on sequence types, but it would fail on e.g. strings in Python 2. I would like to know the right answer too, until then, here is one possibility (which would work on strings, too):

        some_object_iterator = iter(some_object)
    except TypeError as te:
        print some_object, 'is not iterable'

    The iter built-in checks for the __iter__ method or in the case of strings the __getitem__ method.

  2. Another general pythonic approach is to assume an iterable, then fail gracefully if it does not work on the given object. The Python glossary:

    Pythonic programming style that determines an object's type by inspection of its method or attribute signature rather than by explicit relationship to some type object ("If it looks like a duck and quacks like a duck, it must be a duck.") By emphasizing interfaces rather than specific types, well-designed code improves its flexibility by allowing polymorphic substitution. Duck-typing avoids tests using type() or isinstance(). Instead, it typically employs the EAFP (Easier to Ask Forgiveness than Permission) style of programming.


       _ = (e for e in my_object)
    except TypeError:
       print my_object, 'is not iterable'
  3. The collections module provides some abstract base classes, which allow to ask classes or instances if they provide particular functionality, for example:

    from import Iterable
    if isinstance(e, Iterable):
        # e is iterable

    However, this does not check for classes that are iterable through __getitem__.

1/22/2019 1:56:23 AM

Duck typing

    iterator = iter(theElement)
except TypeError:
    # not iterable
    # iterable

# for obj in iterator:
#     pass

Type checking

Use the Abstract Base Classes. They need at least Python 2.6 and work only for new-style classes.

from import Iterable   # import directly from collections for Python < 3.3

if isinstance(theElement, Iterable):
    # iterable
    # not iterable

However, iter() is a bit more reliable as described by the documentation:

Checking isinstance(obj, Iterable) detects classes that are registered as Iterable or that have an __iter__() method, but it does not detect classes that iterate with the __getitem__() method. The only reliable way to determine whether an object is iterable is to call iter(obj).

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow