How to check if an object is iterable in Python

avatar
Borislav Hadzhiev

Last updated: Apr 8, 2024
3 min

banner

# 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) print('The object is iterable') for i in my_iterator: print(i) # ๐Ÿ‘‰๏ธ h, e, l, l, o except TypeError as te: print('The object is NOT iteralbe')

check if object is iterable

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 you have to do this often, define a reusable function.

main.py
def is_iterable(value): try: iter(value) return True except TypeError: return False print(is_iterable('hello')) # ๐Ÿ‘‰๏ธ True print(is_iterable(100)) # ๐Ÿ‘‰๏ธ False my_str = 'hello' if is_iterable(my_str): print('The value is iteralbe') else: print('The value is not iterable')

The is_iterable function takes a value and returns True if the value is iterable and False otherwise.

# Passing a non-iterable object to the iter() function raises an error

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) print('The object is iterable') for i in my_iterator: print(i) except TypeError as te: # ๐Ÿ‘‡๏ธ This runs print('The object is NOT iterable') print(te) # ๐Ÿ‘‰๏ธ 'int' object is not iterable

passing non iterable object to iter function raises the error

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).

# Using the Iterable class to check if an object is iterable

Other options 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 if isinstance(my_list, Iterable): # ๐Ÿ‘‡๏ธ This runs print('The object is iterable') else: print('The object is NOT iterable')

Make sure to import the Iterable class before using it.

The collections.abc.Iterable class enables us to check if another class is registered as Iterable or has an __iter__() method.

However, 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.

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

# Most iterable built-in objects implement the __iter__ 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.

# Making a class iterable by implementing the __iter__ method

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.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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.

Copyright ยฉ 2024 Borislav Hadzhiev