How does one check if a Python object supports iteration, a.k.a an iterable object (see definition
Ideally I would like function similar to isiterable(p_object)
returning True or False (modelled after isinstance(p_object, type)
).
As of Python 3.4, the most accurate way to check whether an object x is iterable is to call iter(x) and handle a TypeError exception if it isn't. This is more accurate than using isinstance(x, abc. Iterable) , because iter(x) also considers the legacy __getitem__ method, while the Iterable ABC does not.
An object is Iterable if it can give you Iterator . It does so when you use iter() on it. An object is Iterator if you can use next() to sequentially browse through its elements. For example, map() returns Iterator and list is Iterable .
Python isinstance() Function The isinstance() function returns True if the specified object is of the specified type, otherwise False . If the type parameter is a tuple, this function will return True if the object is one of the types in the tuple.
You can check for this using isinstance
and collections.Iterable
>>> from collections.abc import Iterable # for python >= 3.6 >>> l = [1, 2, 3, 4] >>> isinstance(l, Iterable) True
Note: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated since Python 3.3, and in 3.9 it will stop working.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With