How to tell if a value is iterable in Python?

How can I do to check in Python if a certain value is iterable?

What determines that a given type can be iterable?

For example, how to find out this in the case below?

a = 1 
b = 'Uma string'
c = [1, 2, 3]
d = xrange(1, 10)
e = range(1, 10)
f = {"a" : 1}
g = True
Author: Wallace Maxters, 2017-01-11

2 answers

I haven't seen any articles or papers yet citing exactly how to do this in a "great"way. Meanwhile, miku , from StackOverflow in English, cited some examples.

You can try something like:

1-assuming the object is always iterable and then capturing the error if not, in the style Pythonic - EAFP (Easier to Ask Forgiveness than Permission) - "better to ask forgiveness than permission "

try:
    _ = (e for e in my_object)
except TypeError:
    print my_object, 'is not iterable'

Or:

2-using the module collections

import collections

if isinstance(e, collections.Iterable):
    # e is iterable
 6
Author: Leonardo Pessoa, 2017-05-23 12:37:26

Two Pythonic ways of checking this.

With try-except

try:
    iterator = iter(var)
except TypeError:
    # não iterável
else:
    # iterável

Checking by abstract class

Only works with classes new style - which do not exist in versions smaller than 2.2.

import collections

if isinstance(var, collections.Iterable):
    # iterável
else:
    # não iterável
 4
Author: LINQ, 2017-01-12 11:15:45