3

consider this example?

p = [1,2,3,4], (1,2,3), set([1,2,3])]

instead of checking for each types like

for x in p:
   if isinstance(x, list):
      xxxxx
   elif isinstance(x, tuple):
      xxxxxx
   elif isinstance(x, set):
      xxxxxxx

Is there some equivalent for the following:

for element in something:
  if isinstance(x, iterable):
      do something
brain storm
  • 30,124
  • 69
  • 225
  • 393
  • 1
    The simplest approach is just to try iterating over it and catch the exception if it doesn't work. – BrenBarn Nov 12 '13 at 01:35

2 Answers2

17

You could try using the Iterable ABC from the collections module:

In [1]: import collections

In [2]: p = [[1,2,3,4], (1,2,3), set([1,2,3]), 'things', 123]

In [3]: for item in p:
   ...:     print isinstance(item, collections.Iterable)
   ...:     
True
True
True
True
False
RocketDonkey
  • 36,383
  • 7
  • 80
  • 84
  • 7
    Importing `Iterable` from `collections` is deprecated and will break in Python 3.8+. Instead, import from `collections.abc`, e.g. `from collections.abc import Iterable`. – Demitri Aug 13 '19 at 06:21
  • If you wish to use `collections.abc.Iterable` as a generic type (e.g., `Iterable[int]`) in Python 3.8 or earlier, you must also do `from __future__ import annotations` – BallpointBen Feb 22 '21 at 16:44
  • @BallpointBen I think you're confusing `collections.abc.Iterable` with `typing.Iterable`. – c z Feb 26 '21 at 10:06
  • 2
    @cz Python is changing so fast these days... Take a look at [Pep 585](https://www.python.org/dev/peps/pep-0585/), it says importing types that exist in `collections.abc` from `typing` is deprecated; importing them from `collections.abc` is the right way to do it in Python 3.9+, and in Python 3.7+ with `from __future__ import annotations`. – BallpointBen Feb 26 '21 at 15:10
6

You can check if the object has __iter__ attribute in it, to make sure if it is iterable or not.

a = [1, 2, 3]
b = {1, 2, 3}
c = (1, 2, 3)
d = {"a": 1}
f = "Welcome"
e = 1
print (hasattr(a, "__iter__"))
print (hasattr(b, "__iter__"))
print (hasattr(c, "__iter__"))
print (hasattr(d, "__iter__"))
print (hasattr(f, "__iter__") or isinstance(f, str))
print (hasattr(e, "__iter__"))

Output

True
True
True
True
True
False

Note: Even though Strings are iterable, in python 2 they dont have __iter__, but in python 3 they have it. So, in python 2 you might want to have or isinstance(f, str) as well

thefourtheye
  • 233,700
  • 52
  • 457
  • 497