5

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
1
  • 1
    The simplest approach is just to try iterating over it and catch the exception if it doesn't work. Commented Nov 12, 2013 at 1:35

2 Answers 2

19

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
Sign up to request clarification or add additional context in comments.

4 Comments

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.
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 I think you're confusing collections.abc.Iterable with typing.Iterable.
@cz Python is changing so fast these days... Take a look at Pep 585, 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.
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

7 Comments

This fails for strings, which are iterable but don't have __iter__.
@Mark i think they have.
>>> str.__iter__ <slot wrapper '__iter__' of 'str' objects>
@MarkReed I added a note for string part.
@aIKid In python 3, we have but not it python 2
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.