In Python, how do I determine if an object is iterable?

前端 未结 21 2596
太阳男子
太阳男子 2020-11-22 00:35

Is there a method like isiterable? The only solution I have found so far is to call

hasattr(myObj, \'__iter__\')

But I am not

21条回答
  •  不要未来只要你来
    2020-11-22 01:01

    You could try this:

    def iterable(a):
        try:
            (x for x in a)
            return True
        except TypeError:
            return False
    

    If we can make a generator that iterates over it (but never use the generator so it doesn't take up space), it's iterable. Seems like a "duh" kind of thing. Why do you need to determine if a variable is iterable in the first place?

提交回复
热议问题