How to check if an object is iterable in Python? [4 Methods]

An iterable in Python is an object containing a sequence of elements that can be iterated using a simple for loop. Lists, integers, strings, and dictionaries are examples of such objects.

In this Python article, I will demonstrate how to check if an object is iterable in Python with various methods and illustrative examples.

I will explain the list of methods to check if an object is iterable in Python.

  • Using the iter() function
  • Using for loop
  • Using the collection.abc module with isinstance() function
  • Using duck typing

Python Program to check if an object is iterable using the iter() function

Python provides the built-in iter() function that can be used to check if an object is iterable. The parameters provided in the iter method in Python are object and sentinel.

Here is the full code of Python to check if an object is iterable using the iter() function.

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

print("List:",is_iterable([1, 2, 3]))
print("String:",is_iterable("hello"))
print("Integer:",is_iterable(42))
print("Dictionary:",is_iterable({'a': 1})) 

We used the try and expect statement in Python to handle exceptions.

In this Python program try part, we can add Python code that might raise an exception, whereas the expected part is the Python code with the iter() function in the try part to check if the object is iterable in Python.

 try:
  iter(object)
  return True
 except TypeError:
  return False

Output:

List: True
String: True
Integer: False
Dictionary: True

Refer to the screenshot below to see the output of the Python program to check if an object is iterable using the iter() function.

How to check if an object is iterable in Python

Check if an object is iterable in Python using for loop

In this example, we will try to iterate an object using a for loop and check whether it is iterated or not in Python.

READ:  How to Import a Class from a File in Python [4 ways]

To do this, I can use the below Python program to check if an object is iterable in Python using a for loop.


text = "John Smith"
try:
   for i in text:
      print(i)
   print("Given object is iterable")
except TypeError:
   print("Given object is not iterable")  

Output:

J
o
h
n
 
S
m
i
t
h
Given object is iterable

You can see the output of the Python program to check if an object is iterable using a for-loop.

Python program to check if an object is iterable using a for loop

How to check if an object is iterable in Python using the collections.abc module with isinstance() function

In Python, the 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 in Python.

To check if an object is iterable using collection.abc, we can use the isinstance() function in Python.

In Python, the built-in function isinstance() is used to check if an object belongs to some Iterable class.

This is the complete Python source code to check if an object is iterable in Python using the isinstance() function of collections.abc module.

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

print("List:",is_iterable([1, 2, 3]))
print("String:",is_iterable("hello")) 
print("Integer:",is_iterable(42))
print("Dictionary:",is_iterable({'a': 1})) 

Here, I will check if the object passed to the function is an example of an iterable object. Then, it returns True if an object is iterable in Python. Otherwise False.

return isinstance(object, Iterable)

Output:

List: True
String: True
Integer: False
Dictionary: True

The screenshot below shows the output of the program to check if an object is iterable in Python using the collections.abc module with isinstance() function.

Check if an object is iterable in Python using the collections.abc module with isinstance() function

Python Program to check if an object is iterable using the duck typing

In Python, duck typing means that the type or class of an object is determined by its behavior rather than its specific types. This implies that if an object behaves like an iterable, it can be considered one.

READ:  How to Exit an If Statement in Python [7 different ways]

Here is the complete program to check if an object is iterable in Python using duck typing.

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

print("List:",is_iterable([5, 2, 3]))
print("String:",is_iterable("Latham")) 
print("Integer:",is_iterable(42))
print("Dictionary:",is_iterable({'a': 1}))

I have used hasattr() function to check if the object has the __iter__ attribute in Python. It returns True if the object has the specified attribute, in this case, iter, which indicates it is iterable. Otherwise, it returns False.

return hasattr(obj, "__iter__")

Output:

List: True
String: True
Integer: False
Dictionary: True

Refer to the screenshot below to see the output of the program to check if an object is iterable in Python using duck typing.

How to check if an object is iterable in Python using duck typing

Conclusion

I hope this tutorial provided the information to check if an object is iterable in Python. Here, I have also illustrated the different ways to check the iterability of an object in Python such as using the iter() function, for loop, collections.abc module with isinstance function and duck typing.

Knowing how to check if an object is iterable can be useful to avoid TypeError when you have a for loop or list comprehension with the object in Python.

You may also like to read: