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

  • Count files in folder in PowerShell
    01 January

    PowerShell – Count Files in Folders

    Table of ContentsCount Files in Folders in PowerShellCount Files in multiple Folders in PowerShellCount Files in Folders and Subfolders in PowerShellCount only folders inside folder in PowerShellCount Files by Extension in Folder in PowerShell Count Files in Folders in PowerShell We can use the Measure-Object cmdlet in different ways to meet our project requirements. However, […]

  • Check if Object contains property in PowerShell
    31 December

    Check if Object has Property in PowerShell

    Table of ContentsUsing the -match ParameterUsing -contains ParameterUsing if-else BlockUsing .Match() Function with if-else BlockUsing Get-Member Cmdlet Using the -match Parameter Use the -match parameter to check if an object has a property in PowerShell. [crayon-63b362cdb3a09948670799/] [crayon-63b362cdb3a0e748655312/] Here, we used the -match parameter to check if the given object, which is $result in our case, […]

  • Create Empty File in PowerShell
    28 December

    Create Empty File in PowerShell

    Table of ContentsUsing New-Item CmdletUse the ni AliasUsing Out-File CmdletUsing the fsutil file CommandUsing Text EditorUsing echo CommandUsing for Loop Using New-Item Cmdlet Use the New-Item cmdlet to create an empty .txt file in PowerShell. [crayon-63b362cdb400a348395252/] [crayon-63b362cdb4010034771597/] We used the New-Item cmdlet with -Path, -Name, and -ItemType parameters to create an empty .txt file using […]

  • 27 December

    Run PowerShell as Another User

    Table of ContentsUsing the runas CommandOpen the PowerShell as an AdministratorRun the runas commandUsing the Start-Process cmdlet with the Credential ParameterUI-Based SolutionScript-Based Solution Using the runas Command The runas command in PowerShell launches programs using credentials different from the current user. It provides users with limited privileges to execute commands or access resources available only […]

  • 27 December

    Create Array of All NaN Values in Python

    Table of ContentsUsing numpy.empty() FunctionUsing numpy.full() FunctionUsing numpy.tile() FunctionUsing numpy.repeat() FunctionUsing Multiplication of numpy.ones() with nan Using numpy.empty() Function To create an array of all NaN values in Python: Use numpy.empty() to get an array of the given shape. Assign numpy.nan to every array element using the assignment operator (=). [crayon-63b362cdb4b0a635653890/] [crayon-63b362cdb4b0f355955243/] We used numpy.empty() […]

  • 27 December

    Call Function from Another Function in Python

    Table of ContentsCall a Function in PythonCall Function from Another Function in PythonCall a Function from Another Function within the Same/Different Classes Call a Function in Python To call a function in Python: Write a test() function, which prints a message. Call the function defined in the previous step. [crayon-63b362cdb4c90133531177/] [crayon-63b362cdb4c93620760794/] To call a function, […]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.