Python 3.3+collectionsterm
collections.abc.Iterable
collections.abc — protocols
The protocol for objects usable in a for loop (has __iter__).
Syntax
isinstance(obj, collections.abc.Iterable)
The isinstance check looks for __iter__ and nothing else, so a legacy class defining only __getitem__ reports False even though a for loop happily walks it; calling iter(obj) inside try/except TypeError is the more honest test. Also, str is Iterable, so a recursive flattener that descends into anything Iterable will spin forever on single characters.
Examples
import collections.abc as abc
print(isinstance([1, 2], abc.Iterable)) # → True
print(isinstance('hi', abc.Iterable)) # → True
print(isinstance(42, abc.Iterable)) # → False
print(issubclass(range, abc.Iterable)) # → True
print([x for x in [1, [2, 3], 'ab'] if isinstance(x, abc.Iterable)]) # → [[2, 3], 'ab']
See also
Open in the full glossarydocs.python.orgReport an inaccuracy