How to check if an object is iterable in Python

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

Check if an object is iterable in Python #

To check if an object is iterable in Python:

  1. Pass the object to the iter() function.
  2. The iter function raises a TypeError if the passed-in object is not iterable.
  3. Handle the TypeError using a try/except statement.
main.py
my_str = 'hello' try: my_iterator = iter(my_str) for i in my_iterator: print(i) # 👉️ h, e, l, l, o except TypeError as te: print(te)

The iter() function raises a TypeError if the passed in value doesn't support the __iter__() method or the sequence protocol (the __getitem__() method).

If we pass a non-iterable object like an integer to the iter() function, the except block is run.

main.py
my_int = 100 try: my_iterator = iter(my_int) for i in my_iterator: print(i) except TypeError as te: print(te) # 👉️ 'int' object is not iterable

Examples of iterables include all sequence types (list, str, tuple) and some non-sequence types like dict, file objects and other objects that define an __iter__() or a __getitem__() method.

The only reliable way to determine whether an object is iterable is to call iter(obj).

There are other options that are not as complete. For example, you can use the Iterable class from the collections.abc module.

main.py
from collections.abc import Iterable my_list = ['a', 'b', 'c'] print(isinstance(my_list, Iterable)) # 👉️ True print(isinstance(100, Iterable)) # 👉️ False

The collections.abc.Iterable class enables us to check if another class is registered as Iterable or has an __iter__() method, but it doesn't detect classes that iterate with the __getitem__() method.

This is why the most reliable way to check if an object is iterable is to pass the object to the iter() built-in function which would raise a TypeError if the passed-in value doesn't support the __iter__() method or the sequence protocol (the __getitem__() method).

Having considered that, most of the built-in objects that are iterable implement the __iter__() method.

main.py
print({}.__iter__) print(().__iter__) print([].__iter__) print(''.__iter__) print({'a', }.__iter__)

You can either try to access the method as an attribute to see if the object has it or print the object's attributes with the dir() function, e.g. print(dir(my_object)) and check if it has an __iter__ attribute.

Here is an example of how to make a class iterable by implementing the __iter__() method.

main.py
class Counter: def __init__(self, start, stop): self.current = start - 1 self.stop = stop def __iter__(self): return self def __next__(self): self.current += 1 if self.current < self.stop: return self.current raise StopIteration for c in Counter(0, 4): print(c) # 👉️ 0, 1, 2, 3

The __iter__() method is implicitly called at the start of loops and returns the iterator object.

The __next__() method is implicitly called at each loop increment and returns the next value.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.