Kodeclik Logo

Our Programs

Courses

Learn More

Schedule

Kodeclik Blog

How to determine if a Python object is iterable

One of the key strengths of Python is its support for different data structures, including iterables. An iterable is an object that can be iterated over, meaning it allows you to access its elements one by one.

In this blog post, we will delve into the concept of iterables and explore various methods to check if an object is iterable in Python.

First, let us look at some examples of objects that are not iterables. An integer is an example of an object that is not iterable. For instance consider the following code:

number = 42

for n in number:
    print(n)

If you attempt to run this code, you will get:

Traceback (most recent call last):
  File "main.py", line 3, in <module>
    for n in number:
TypeError: 'int' object is not iterable

As the error message clearly says, the int object is not iterable.

Thus, in Python, an iterable is any object capable of returning its elements sequentially. This can be achieved using the for loop or by using various iterable-related functions and methods.

Common examples of iterables in Python include lists, tuples, strings, dictionaries, sets, and even file objects. Each of these data structures can be traversed using the for loop, making them iterables.

How to check if a Python object is iterable

The Iteration Protocol

Python's ability to iterate over objects is made possible by following the iteration protocol. This protocol requires an iterable object to have two essential methods:

__iter__: This method returns an iterator object, which is responsible for producing the elements of the iterable one by one during the iteration.

__next__: The iterator object obtained from __iter__ must implement the __next__ method, which returns the next element of the iterable. When there are no more elements to return, it raises the StopIteration exception to signal the end of iteration.

By adhering to the iteration protocol, Python enables developers to use the for loop or any other iterable-based function to traverse the elements of these objects without needing to know the internal details of each data structure.

Method 1: Use the iter() function

The simplest way to check for iterability is by using the iter() function. See the example code below.

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

print(is_iterable(42))
print(is_iterable([4,2]))
print(is_iterable("42"))

In the above code, the is_iterable() function attempts to convert the given object into an iterator using the __iter__ method. If successful, it implies that the object is iterable; otherwise, a TypeError is raised. We then catch this error using exception handling and returns a False in that case. Otherwise a True is returned. The output is:

False
True
True

As shown above lists and strings are iterable because they can provide access to their elements one by one but integers are not.

Method 2: Use the collections.abc module

Python's collections.abc module provides the Iterable abstract base class, which can be utilized to perform the iterability check. The Iterable class from this module can be subclassed to create new iterable classes.

To check if an object is iterable using collections.abc, we can leverage the isinstance() function as shown below:

from collections.abc import Iterable

def is_iterable(obj):
    return isinstance(obj, Iterable)

print(is_iterable(42))
print(is_iterable([4,2]))
print(is_iterable("42"))

The output is again:

False
True
True

Method 3: Use duck typing

Python is dynamically typed, and it follows the principle of "duck typing." This means that the type or class of an object is determined by its behavior rather than its explicit type. In the context of iterables, this implies that if an object behaves like an iterable, it can be considered as one.

We can perform duck typing by checking if the object has the __iter__ method, indicating that it can return an iterator:

def is_iterable(obj):
  return hasattr(obj, "__iter__")

print(is_iterable(42))
print(is_iterable([4,2]))
print(is_iterable("42"))

The output is again:

False
True
True

We have learnt the concept of iterables and discussed different methods to check if an object is iterable in Python. From using the iter() function to employing collections.abc and leveraging the principles of duck typing, you have multiple options to determine if an object supports iteration. Use these ideas to make your programs more robust and tolerant to errors!

If you liked this blogpost, learn how to iterate through a Python list in reverse order, or how to reverse a range. Both these concepts use the ideas of iterable to accomplish their goals.

Interested in more things Python? Checkout our post on Python queues. Also see our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!

Want to learn Python with us? Sign up for 1:1 or small group classes.

Kodeclik sidebar newsletter

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.

About

Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.

Copyright @ Kodeclik 2024. All rights reserved.