Test a variable for iterability.
Determine whether an object
xis iterable. In Python 2, this was as simple as checking for the
__iter__attribute. However, in Python 3, strings became iterable. Therefore, this function checks for the
__iter__attribute, returning True if present (except for strings, for which it will return False).
x : str, iterable or object
The object in question.
isiter : bool
True if iterable, else False.
Strings and other objects are not iterable:
>>> x = "not me" >>> y = 123 >>> any(is_iterable(v) for v in (x, y)) False
Tuples, lists and other structures with
>>> x = ('a', 'tuple') >>> y = ['a', 'list'] >>> all(is_iterable(v) for v in (x, y)) True
This even applies to numpy arrays:
>>> import numpy as np >>> is_iterable(np.arange(10)) True