One of the key strengths of Python is its support for different data structures, including iterables. An iterable is an object that can be iterated over, meaning it allows you to access its elements one by one.
In this blog post, we will delve into the concept of iterables and explore various methods to check if an object is iterable in Python.
First, let us look at some examples of objects that are not iterables. An integer is an example of an object that is not iterable. For instance consider the following code:
If you attempt to run this code, you will get:
As the error message clearly says, the int object is not iterable.
Thus, in Python, an iterable is any object capable of returning its elements sequentially. This can be achieved using the for loop or by using various iterable-related functions and methods.
Common examples of iterables in Python include lists, tuples, strings, dictionaries, sets, and even file objects. Each of these data structures can be traversed using the for loop, making them iterables.
The Iteration Protocol
Python's ability to iterate over objects is made possible by following the iteration protocol. This protocol requires an iterable object to have two essential methods:
__iter__: This method returns an iterator object, which is responsible for producing the elements of the iterable one by one during the iteration.
__next__: The iterator object obtained from __iter__ must implement the __next__ method, which returns the next element of the iterable. When there are no more elements to return, it raises the StopIteration exception to signal the end of iteration.
By adhering to the iteration protocol, Python enables developers to use the for loop or any other iterable-based function to traverse the elements of these objects without needing to know the internal details of each data structure.
Method 1: Use the iter() function
The simplest way to check for iterability is by using the iter() function. See the example code below.
In the above code, the is_iterable() function attempts to convert the given object into an iterator using the __iter__ method. If successful, it implies that the object is iterable; otherwise, a TypeError is raised. We then catch this error using exception handling and returns a False in that case. Otherwise a True is returned. The output is:
As shown above lists and strings are iterable because they can provide access to their elements one by one but integers are not.
Method 2: Use the collections.abc module
Python's 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.
To check if an object is iterable using collections.abc, we can leverage the isinstance() function as shown below:
The output is again:
Method 3: Use duck typing
Python is dynamically typed, and it follows the principle of "duck typing." This means that the type or class of an object is determined by its behavior rather than its explicit type. In the context of iterables, this implies that if an object behaves like an iterable, it can be considered as one.
We can perform duck typing by checking if the object has the __iter__ method, indicating that it can return an iterator:
The output is again:
We have learnt the concept of iterables and discussed different methods to check if an object is iterable in Python. From using the iter() function to employing collections.abc and leveraging the principles of duck typing, you have multiple options to determine if an object supports iteration. Use these ideas to make your programs more robust and tolerant to errors!
Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.