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

前端 未结 21 2206
太阳男子
太阳男子 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:42

    The isiterable func at the following code returns True if object is iterable. if it's not iterable returns False

    def isiterable(object_):
        return hasattr(type(object_), "__iter__")
    

    example

    fruits = ("apple", "banana", "peach")
    isiterable(fruits) # returns True
    
    num = 345
    isiterable(num) # returns False
    
    isiterable(str) # returns False because str type is type class and it's not iterable.
    
    hello = "hello dude !"
    isiterable(hello) # returns True because as you know string objects are iterable
    

提交回复
热议问题