How to Determine if an Object is Iterable in Python

Created
Modified

Using Duck Typing

Duck typing is a concept related to dynamic typing, where the type or the class of an object is less important than the methods it defines. When you use duck typing, you do not check types at all. Instead, you check for the presence of a given method or attribute.

See the following example:

#!/usr/bin/python3

a = "abcd"
try:
  i = iter(a)
  print("Iterable")
except TypeError:
  print("Not Iterable")

a = 1
try:
  i = iter(a)
  print("Iterable")
except TypeError:
  print("Not Iterable")
Iterable
Not Iterable

Using Type Checking

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

#!/usr/bin/python3

# Import module
from collections.abc import Iterable

a = 1
print(isinstance(a, Iterable))

a = "1"
print(isinstance(a, Iterable))
False
True

Related Tags