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

前端 未结 21 2243
太阳男子
太阳男子 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 00:57

    Not really "correct" but can serve as quick check of most common types like strings, tuples, floats, etc...

    >>> '__iter__' in dir('sds')
    True
    >>> '__iter__' in dir(56)
    False
    >>> '__iter__' in dir([5,6,9,8])
    True
    >>> '__iter__' in dir({'jh':'ff'})
    True
    >>> '__iter__' in dir({'jh'})
    True
    >>> '__iter__' in dir(56.9865)
    False
    

提交回复
热议问题