• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

The Programming Expert

Solving All of Your Programming Headaches

  • HTML
  • JavaScript
  • jQuery
  • PHP
  • Python
  • SAS
  • Ruby
  • About
You are here: Home / Python / Python Check if Object is Iterable with hasattr() Function

Python Check if Object is Iterable with hasattr() Function

February 10, 2022 Leave a Comment

Using Python, the easiest way to check if an object is iterable is to use the Python hasattr() function to check if the object has the “__iter__” attribute.

if hasattr(obj, "__iter__"):
    print("Object is iterable!")
else:
    print("Object is not iterable!")

You can also use the collections module in Python to see if the variable is an instance of the Iterable class.

from collections.abc import Iterable

if isinstance(obj, Iterable):
    print("Object is iterable!")
else:
    print("Object is not iterable!")

The last way you can check if an object is iterable is with the Python iter() function.

try:
    iter(obj)
    print("Object is iterable!")
except TypeError:
    print("Object is not iterable!")

When working with objects in Python, it is useful to be able to easily check if an object is a certain type or instance of a class.

We can check if an object is iterable in Python easily. An iterable object is any object that can be looped over. For example, lists are iterable.

The easiest way to check if an object is iterable is to use the Python hasattr() function and check if the object has the attribute “__iter__”.

Below is some sample Python code which will check if an object is iterable.

def isIterable(obj):
    if hasattr(obj, "__iter__"):
        return "Object is iterable!"
    else:
        return "Object is not iterable!"

print(isIterable([0,1,2]))
print(isIterable(0))
print(isIterable("A string"))

#Output:
Object is iterable!
Object is not iterable!
Object is iterable!

Checking if an Object is Iterable with Python isinstance() Function

We can also check if an object is iterable in Python with the isinstance() function.

We use the collections module in Python and will see if the variable is an instance of the Iterable class.

Below is an example in Python of how to use the isinstance() function to see if an object is iterable.

from collections.abc import Iterable

def isIterable(obj):
    if isinstance(obj, Iterable):
        return "Object is iterable!"
    else:
        return "Object is not iterable!"


print(isIterable([0,1,2]))
print(isIterable(0))
print(isIterable("A string"))

#Output:
Object is iterable!
Object is not iterable!
Object is iterable!

Checking if Object is Iterable with iter() Function in Python

The last way you can check if an object is iterable is with the Python iter() function.

The iter() function checks whether the object implements __iter__, and calls that to obtain an iterator.

If the function fails to find __iter__, then it will raise a TypeError.

Below is an example in Python of checking if an object is iterable with the iter() function.

def isIterable(obj):
    try:
        iter(obj)
        return "Object is iterable!"
    except TypeError:
        return "Object is not iterable!"

print(isIterable([0,1,2]))
print(isIterable(0))
print(isIterable("A string"))

#Output:
Object is iterable!
Object is not iterable!
Object is iterable!

Hopefully this article has been useful for you to learn how to check if an object is iterable or not in Python.

Other Articles You'll Also Like:

  • 1.  Get Name of Function in Python
  • 2.  Get First Key and Value in Dictionary with Python
  • 3.  pandas set_value – Using at() Function to Set a Value in DataFrame
  • 4.  rfind Python – Find Last Occurrence of Substring in String
  • 5.  Sort List of Tuples in Python
  • 6.  pandas nsmallest – Find Smallest Values in Series or Dataframe
  • 7.  Convert List to Set with Python
  • 8.  Creating a List of Zeros in Python
  • 9.  Change Column Name in pandas DataFrame
  • 10.  Using Python to Print Environment Variables

About The Programming Expert

The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.

Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.

At the end of the day, we want to be able to just push a button and let the code do it’s magic.

You can read more about us on our about page.

Reader Interactions

Leave a Reply Cancel reply

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

Primary Sidebar

About The Programming Expert

the programming expert main image

Welcome to The Programming Expert. We are a group of US-based programming professionals who have helped companies build, maintain, and improve everything from simple websites to large-scale projects.

We built The Programming Expert to help you solve your programming problems with useful coding methods and functions in various programming languages.

Search

Learn Coding from Experts on Udemy

Looking to boost your skills and learn how to become a programming expert?

Check out the links below to view Udemy courses for learning to program in the following languages:

Copyright © 2023 · The Programming Expert · About · Privacy Policy