Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an object is iterable in Python? [duplicate]

How does one check if a Python object supports iteration, a.k.a an iterable object (see definition

Ideally I would like function similar to isiterable(p_object) returning True or False (modelled after isinstance(p_object, type)).

like image 858
Boaz Avatar asked Jan 12 '11 12:01

Boaz


People also ask

How do you check if an object is an iterable in Python?

As of Python 3.4, the most accurate way to check whether an object x is iterable is to call iter(x) and handle a TypeError exception if it isn't. This is more accurate than using isinstance(x, abc. Iterable) , because iter(x) also considers the legacy __getitem__ method, while the Iterable ABC does not.

How do I know if I have an iterator?

An object is Iterable if it can give you Iterator . It does so when you use iter() on it. An object is Iterator if you can use next() to sequentially browse through its elements. For example, map() returns Iterator and list is Iterable .

What does Isinstance mean in Python?

Python isinstance() Function The isinstance() function returns True if the specified object is of the specified type, otherwise False . If the type parameter is a tuple, this function will return True if the object is one of the types in the tuple.


1 Answers

You can check for this using isinstance and collections.Iterable

>>> from collections.abc import Iterable # for python >= 3.6 >>> l = [1, 2, 3, 4] >>> isinstance(l, Iterable) True 

Note: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated since Python 3.3, and in 3.9 it will stop working.

like image 69
user225312 Avatar answered Oct 02 '22 13:10

user225312