AppDividend
Latest Code Tutorials

Python is iterable Tutorial with Example

2

Python does not have any built-in method isiterable() to check if the object is iterable or not. But there are several ways that you can use to determine whether the object is iterable or not. Some of the approaches are expensive operations, and some are not feasible in some use cases.

Python is iterable

To check if the object is iterable in Python, use the iter() method. Python iter() is an inbuilt function that returns an iterator for the given object.

The iter() method is the most accurate way to check whether an object is iterable and handle a TypeError exception if it isn’t.

The syntax of the iter() function is the following.

iter(object, sentinel)

Example

data = ["Upendra", "Arjun", "Nikunj"]

try:
    object_iterator = iter(data)
except TypeError as te:
    print(data, "is not iterable")
else:
    print(data, "is iterable")

Output

['Upendra', 'Arjun', 'Nikunj'] is iterable

Let’s assign an integer to the data variable and check for the iterable.

data = 21

try:
    object_iterator = iter(data)
except TypeError as te:
    print(data, "is not iterable")
else:
    print(data, "is iterable")

Output

21 is not iterable

Python collections approach

To check if the object is iterable in Python, use the collections module’s Iterable abstract class. The collections module provides some abstract base classes, which allow asking classes or instances if they provide particular functionality.

Python isinstance() is a built-in method that returns True if the specified object is of the specified type. Otherwise, it returns False. We will use the Iterable abstract class and isinstance() method to check if the object is iterable or not in Python.

To work with the Iterable class, we need to import it first.

from collections.abc import Iterable

Now, let’s define an integer that is not iterable but let’s check it using the Iterable class and isinstance() method with the if-else statement in Python.

from collections.abc import Iterable

data = 12

if isinstance(data, Iterable):
    print("The data is iterable")
else:
    print("The data is not iterable")

Run the program and see the output.

The data is not iterable

As you can see that we got the right answer which is that integer in Python is not an iterable data type.

Now, let’s assign the list to the data variable, which is iterable, and see what output it returns.

from collections.abc import Iterable

data = ["Rick", "and", "Morty"]

if isinstance(data, Iterable):
    print("The data is iterable")
else:
    print("The data is not iterable")

Output

The data is iterable

Yes, the list is iterable, which means our way of determining if the object is iterable is correct.

Why collections approach is not a complete solution

Checking an iterable using isinstance(obj, Iterable) method detects classes that are registered as Iterable or that have an __iter__() method, but it does not detect classes that iterate with the __getitem__() method.

The only accurate approach is determining whether an object is iterable is to call iter(obj).

Duck typing: Python is iterable

Duck typing is a concept related to dynamic typing, where the type or the class of an object is less important than the methods it defines. When you use duck typing, you do not check types at all. Instead, you check for the presence of a given method or attribute.

data = ["Rick", "and", "Morty"]

try:
    iterator = iter(data)
except TypeError:
    # not iterable
    print("The data is not iterable")
else:
    # iterable
    print("The data is iterable")

Output

The data is iterable

Now, if you assign the data variable an integer, it will execute except block with TypeError.

data = 21

try:
    iterator = iter(data)
except TypeError:
    # not iterable
    print("The data is not iterable")
else:
    # iterable
    print("The data is iterable")

Output

The data is not iterable

As expected, duck typing works fine when it comes to determining whether the variable is iterable or not.

Python __iter__

This approach is not recommended since you are using Python language’s private properties, and it does not work with string also since the string is iterable.

That is it for determining the iterable object in the Python tutorial.

2 Comments
  1. Ashraf says

    For the last few years, I follow your article, a Great article.

    1. Krunal says

      Your welcome. Keep learning and sharing.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.