how to check isinstance of iterable in python?

brain storm picture brain storm · Nov 12, 2013 · Viewed 14.5k times · Source

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

Answer

RocketDonkey picture RocketDonkey · Nov 12, 2013

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