How to Check If an Object Is Iterable in Python
Iterables are fundamental to Python's loop mechanics. An iterable is any object capable of returning its members one at a time, such as lists, tuples, and strings. Checking whether an object is iterable is a common task when building functions that accept flexible inputs (e.g., accepting a single string or a list of strings).
This guide explores two robust methods to verify iterability: using isinstance() with the Iterable abstract base class and using a try-except block with iter().
Method 1: Using isinstance() (Recommended)
The most Pythonic and reliable way to check if an object is iterable is using the collections.abc.Iterable class. This method explicitly checks the object's type inheritance.
from collections.abc import Iterable
def is_iterable(obj):
return isinstance(obj, Iterable)
# Test cases
print(f"List: {is_iterable([1, 2, 3])}")
print(f"String: {is_iterable('Hello')}")
print(f"Int: {is_iterable(42)}")
Output:
List: True
String: True
Int: False
Method 2: Using iter() (Duck Typing)
Python follows the "Duck Typing" philosophy: "If it walks like a duck and quacks like a duck, it's a duck."
Instead of checking the type, we try to create an iterator from the object using iter(). If it fails, Python raises a TypeError.
def is_iterable_duck(obj):
try:
iter(obj)
return True
except TypeError:
return False
print(f"Tuple: {is_iterable_duck((1, 2))}")
print(f"Float: {is_iterable_duck(3.14)}")
Output:
Tuple: True
Float: False
This method is slightly more robust for certain edge cases (like older classes that implement __getitem__ but not __iter__), though isinstance() is sufficient for modern Python code.
Common Pitfall: Iterating Strings
A frequent bug occurs when a function expects a list of items but receives a single string. Since strings are iterable (yielding characters), standard checks return True, leading to unexpected behavior (e.g., iterating 'H', 'e', 'l', 'l', 'o' instead of processing the word "Hello").
If you want to check for "containers" but exclude strings, you must add an explicit check.
from collections.abc import Iterable
def is_collection(obj):
# Check if iterable BUT NOT a string
return isinstance(obj, Iterable) and not isinstance(obj, str)
print(f"List is collection? {is_collection(['a', 'b'])}")
print(f"String is collection? {is_collection('abc')}")
Output:
List is collection? True
String is collection? False
Conclusion
To check if an object is iterable in Python:
- Use
isinstance(obj, Iterable)fromcollections.abcfor the standard, readable check. - Use
iter(obj)inside atry-exceptblock if you prefer duck typing or support very old legacy classes. - Exclude
strexplicitly if your logic shouldn't treat strings as sequences of characters.