-1

I read some very old answers on this(10 years), and they say that in python 2.x this quality of iteration was just presumed.

But what about modern python like 3.9 ? Can I assume an item and object can be iterated ?

Abi

Abi Kumar
  • 23
  • 5
  • probably not the best way, but any object with an `__iter__` method is a good candidate for iteration – Paul H Jun 10 '20 at 21:55
  • Asked and answered at https://stackoverflow.com/questions/1952464/in-python-how-do-i-determine-if-an-object-is-iterable – Amitai Irron Jun 10 '20 at 22:04

2 Answers2

2

Please refer below code and pass your object to find whether it is iterable or not.

def isiterable(obj):
  try:
     iter(obj)
     return True
  except TypeError:
     return False

Good Day!

tmrlvi
  • 2,235
  • 17
  • 35
Earnest
  • 131
  • 2
0

The shining new typing module is exactly for that. It contains all types.

from typing import Iterable
isinstance([], Iterable) # True
isinstance(None, Iterable) # False
tmrlvi
  • 2,235
  • 17
  • 35
  • ``typing`` does not exist for runtime checking. The older ``collections.abc`` exists for this, e.g. ``collections.abc.Iterable``. – MisterMiyagi Jun 10 '20 at 22:06
  • Based on [collections.abs.Iterable](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterable) docs, we shouldn't use `isinstance` for iterables, as old style iterable are not identified by it. It seems that @Prince answer is the recommended way. – tmrlvi Jun 10 '20 at 22:31