python Example of Determining If an Object Is Iterable

  • 2021-07-24 11:26:13
  • OfStack

How to judge that an object is an iterable object?

The method is determined by the Iterable type of the collections module:


>>> from collections import Iterable
>>> isinstance('abc',Iterable)
True
>>> isinstance([1,2,3,4],Iterable)
True
>>> isinstance(1234,Iterable)
False
>>> isinstance((1,),Iterable)
True
>>> L = ['a','b','c']
>>> enumerate(L)
<enumerate object at 0x03AA94E0>
>>> isinstance(enumerate(L),Iterable)
True
>>> for m,n in enumerate(L):
...   print m,n 
... 
0 a
1 b
2 c

Related articles: