Check if Object Is Iterable in Python

In this post, we will see how to check if object is iterable in Python.

What are iterables in Python?

An iterable is an object that contains a sequence of elements that can be iterated over using a simple for loop. Lists, tuples, and strings are examples of such objects.

Objects of such classes have the __iter__ or __getitem__ magic functions associated with them. These functions initialize the elements for an object and allow us to access the elements one by one.

How to check if object is iterable in Python?

Let us now discuss how to check if object is iterable in Python. Different methods are discussed below.

Using the iter() function to check if object is iterable in Python

The iter() function takes an object and returns an iterator object. If the provided object is not iterable then a TypeError is thrown. We can use this function with the try and except statements.

In the try block, we can add code that we think might raise an exception, and in the except block, we write the code that needs to be executed if the exception is raised. We can put the code with the iter() function in the try block to check if object is iterable in Python.

For example,

Output:

In the above example, we initialize a list and an integer. The list is an iterable so a list_iterator is created. An integer is not an iterable and an exception is raised, therefore, the code in the except block is executed.

The iter() function fails with strings in Python 2.

Using the for loop to check if object is iterable in Python

As discussed, we can iterate over an iterable using a for loop to access the elements. If this is not possible in an object, then an exception is raised and the object is not iterable.

We can use the try and except block as we did in the previous example to check if object is iterable in Python using the for loop.

We will try to iterate over the object, if an exception is raised then the code in the except block will execute indicating the object is not iterable.

See the code below.

Output:

7
6
2
3
4
Object is not an iterable

As expected in the above example, the code in except block is executed when we iterate over an integer.

Using the isinstance() function to check if object is iterable in Python

The isinstance() function is used to check if an object is an instance of some specified class. We can use this function to check if object is iterable in Python.

We can check the objects by checking if they belong to the Iterable class found in the collections.abc module. This module contains and defines the format for Abstract Base Classes. It is available in Python 2.6 and above. Below Python 3.3, it can be directly found in the collections module.

The Iterable checks if the given object has an __iter__ magic function associated with it or not. It will fail for iterables that have the __getitem__ magic function instead of __iter__.

We use this method below.

Output:

Object is iterable
Object is not iterable

Conclusion

To conclude, we discussed three methods in this tutorial to check if object is iterable in Python. The first two methods use the try and except blocks. We try to perform actions that an iterable object can perform and if an exception is raised we know that it is not iterable.

In the first method, we use the iter() function that returns an iterator. We try to iterate over the object using a for loop in the second method. In the third method, we use the isinstance() function and check if the object is an instance of the Iterable class from the collections.abc module.

Was this post helpful?


import_contacts

You may also like:

Related Posts

  • 25 June

    Convert Roman Number to Integer in Python

    Table of ContentsHow to Convert Roman Number to Integer in PythonHow to convert roman number to integer in python?Using the if...else statement to convert roman number to integer in Python.Using classes and a dictionary to convert roman number to integer in Python.Using the roman module to convert roman number to integer in Python.ConclusionWas this post […]

  • 11 June

    Remove Single Quotes from String in Python

    Table of ContentsRemove single quotes from string in Python.How to remove single quotes from string in Python?Using the replace() function to remove single quotes from string in Python.Using a for loop to remove single quotes from string in Python.Using the join() function to remove single quotes from string in Python.Using the re module functions to […]

  • 11 June

    Escape Backslash Character in Python

    Table of ContentsEscape backslash character in python.How to use escape backslash character in python?Using the escape backslash character in python to represent whitespace characters.Using the escape backslash character in python to turn special characters into ordinary characters.Using the escape backslash character in f-strings in Python.Using the escape backslash character in raw strings in Python.Was this […]

  • 11 June

    Remove Parentheses From String in Java

    Table of ContentsJava StringsRemove Parentheses From a String Using the replaceAll() MethodRemove Parentheses From a String by TraversingConclusionWas this post helpful? Java uses the Strings data structure to store the text data. This article discusses methods to remove parentheses from a String in Java. Java Strings Java Strings is a class that stores the text […]

  • 11 June

    Break out of function in Python

    Table of ContentsBreak out of function in PythonHow to break out of function in Python?Using the return statement to break out of function in PythonUsing the try and except block to break out of function in PythonUsing the sys.exit() function to break out of function in PythonConclusionWas this post helpful? In this post, we will […]

  • 11 June

    Save Numpy Array as Image in Python

    Table of ContentsSave numpy array as image in PythonHow to save numpy array as image in Python?Using the PIL library to save numpy array as image in PythonUsing the matplotlib.image library to save numpy array as image in PythonUsing the opencv library to save numpy array as image in PythonUsing the imageio library to save […]

Leave a Reply

Your email address will not be published.

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.