How do I know if a value is iterable in Python?

5

How can I do to check in Python if a particular value is iterate?

What determines that a given type can be iterate?

For example, how do you figure this out 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
    
asked by anonymous 11.01.2017 / 13:02

2 answers

6

I have not yet seen any article or document citing exactly how to do this in a "great" way. Meanwhile, miku , from StackOverflow in English ,

You can try something like:

1- Assuming that the object is always iterable, and then capturing the error if it is not in the Python style - EAFP (Easier to Ask Forgiveness than Permission) - "better to ask for 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
    
11.01.2017 / 13:04
4

Two Pythonic ways to check this out.

With try-except

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

Checking for the abstract class

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

import collections

if isinstance(var, collections.Iterable):
    # iterável
else:
    # não iterável
    
11.01.2017 / 13:06