According to the Python documentation:
The only reliable way to determine whether an object is iterable is to call
iter(obj)
.
Therefore, always prefer using the try-except
method to identify an object as an iterable.
Using try-except
Using hasattr
This is a straightforward way but can be a bit hard to read.
Using isinstance
This method is more readable.
However, collections.abc.Iterable
does not consider the legacy __getitem__
method – which is sufficient to create an iterable –, unlike an iter()
call handling a TypeError
exception.