Python check if object is iterable

In Python, how do I determine if an object is iterable?

In Python, an object is considered iterable if it has an __iter__() method defined or if it has a __getitem__() method with defined indices (i.e., it can be indexed, like a list or a string).

The built-in iter() function can be used to check if an object is iterable. If the object is iterable, iter() returns an iterator object; otherwise, it raises a TypeError. For example:

def is_iterable(obj): try: iter(obj) return True except TypeError: return False print(is_iterable(2))

You can also use collections.abc.Iterable ABC and check using the issubclass function.

from collections.abc import Iterable def is_iterable(obj): return issubclass(type(obj), Iterable)

You can then use this function to check if any object is iterable or not.

from collections.abc import Iterable def is_iterable(obj): return issubclass(type(obj), Iterable) is_iterable([1, 2, 3]) is_iterable('abc') is_iterable(5)

It’s worth noting that any class that is not a string, dict, or other fundamental type and which is defined by you or someone else will be considered iterable by this method because it could define the iter method.

Читайте также:  Javascript count on button click

BookDuck

  • Does Python have a ternary conditional operator?
  • What are metaclasses in Python?
  • How do I check whether a file exists without exceptions?
  • How to iterate over rows in a DataFrame in Pandas
  • Convert bytes to a string
  • How do I sort a dictionary by value?
  • Why is «1000000000000000 in range(1000000000000001)» so fast in Python 3?
  • How to leave/exit/deactivate a Python virtualenv
  • Determine the type of an object?
  • How to determine a Python variable’s type?
  • How to check if a string is a substring of items in a list of strings

Источник

Python check if object is iterable

Last updated: Feb 2, 2023
Reading time · 3 min

banner

# Check if an object is iterable in Python

To check if an object is iterable in Python:

  1. Pass the object to the iter() function.
  2. The iter function raises a TypeError if the passed-in object is not iterable.
  3. Handle the TypeError using a try/except statement.
Copied!
my_str = 'hello' try: my_iterator = iter(my_str) print('The object is iterable') for i in my_iterator: print(i) # 👉️ h, e, l, l, o except TypeError as te: print('The object is NOT iteralbe')

The iter() function raises a TypeError if the passed-in value doesn’t support the __iter__() method or the sequence protocol (the __getitem__() method).

If you have to do this often, define a reusable function.

Copied!
def is_iterable(value): try: iter(value) return True except TypeError: return False print(is_iterable('hello')) # 👉️ True print(is_iterable(100)) # 👉️ False my_str = 'hello' if is_iterable(my_str): print('The value is iteralbe') else: print('The value is not iterable')

The is_iterable function takes a value and returns True if the value is iterable and False otherwise.

# Passing a non-iterable object to the iter() function raises an error

If we pass a non-iterable object like an integer to the iter() function, the except block is run.

Copied!
my_int = 100 try: my_iterator = iter(my_int) print('The object is iterable') for i in my_iterator: print(i) except TypeError as te: # 👇️ this runs print('The object is NOT iterable') print(te) # 👉️ 'int' object is not iterable

Examples of iterables include all sequence types ( list , str , tuple ) and some non-sequence types like dict , file objects and other objects that define an __iter__() or a __getitem__() method.

# Using the Iterable class to check if an object is iterable

Other options are not as complete. For example, you can use the Iterable class from the collections.abc module.

Copied!
from collections.abc import Iterable my_list = ['a', 'b', 'c'] print(isinstance(my_list, Iterable)) # 👉️ True print(isinstance(100, Iterable)) # 👉️ False if isinstance(my_list, Iterable): # 👇️ this runs print('The object is iterable') else: print('The object is NOT iterable')

Make sure to import the Iterable class before using it.

The collections.abc.Iterable class enables us to check if another class is registered as Iterable or has an __iter__() method.

However, it doesn’t detect classes that iterate with the __getitem__() method.

This is why the most reliable way to check if an object is iterable is to pass the object to the iter() built-in function.

The iter() function raises a TypeError if the passed-in value doesn’t support the __iter__() method or the sequence protocol (the __getitem__() method).

# Most iterable built-in objects implement the __iter__ method

Having considered that, most of the built-in objects that are iterable implement the __iter__() method.

Copied!
print(>.__iter__) print(().__iter__) print([].__iter__) print(''.__iter__) print('a', >.__iter__)

You can either try to access the method as an attribute to see if the object has it or print the object’s attributes with the dir() function, e.g. print(dir(my_object)) and check if it has an __iter__ attribute.

# Making a class iterable by implementing the __iter__ method

Here is an example of how to make a class iterable by implementing the __iter__() method.

Copied!
class Counter: def __init__(self, start, stop): self.current = start - 1 self.stop = stop def __iter__(self): return self def __next__(self): self.current += 1 if self.current self.stop: return self.current raise StopIteration for c in Counter(0, 4): print(c) # 👉️ 0, 1, 2, 3

The __iter__() method is implicitly called at the start of loops and returns the iterator object.

The __next__() method is implicitly called at each loop increment and returns the next value.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

How to check if an object is iterable in Python

An iterable object is any object that can be iterated over using a for loop. Some examples of iterable objects in Python are strings, lists, and tuples.

When developing with Python, you may get a variable or custom object, but you don’t know if it’s iterable or not.

Knowing if a given object is iterable or not is important because Python will raise a TypeError when you try to iterate over a non-iterable object.

In this article, you will learn different ways to check if an object is iterable in Python.

1. Using the iter() function

The iter() function takes an object as an argument and returns an iterator object if the object is iterable.

Under the hood, the iter() function checks if the object has __iter__() or __getitem__() method implemented. If not, the function will return a TypeError .

You need to wrap the call to this function in a try-except block as follows:

Since the list object is iterable, Python won’t execute the except block.

2. Using the isinstance() function

You can also use the isinstance() function together with the Iterable class to check if an object is iterable or not.

This function takes two parameters: an object and a type.

The function returns True if the object is an instance of the given type. Otherwise, it returns False .

Here’s an example of using the isinstance() function to check if a string is an instance of the Iterable class:

Note that you need to import the Iterable class from the collections.abc module.

Also, this solution is less preferred than the iter() function because the Iterable class only checks for the modern __iter__() method while ignoring the existence of the __getitem__() method in the object.

If you don’t need to support old versions of Python, then using this solution may not cause any issues.

3. Make checking easy with isiterable()

If you have many variables and objects with unknown data types, it will be inconvenient to check the objects one by one.

I recommend you create a custom function that returns True when an object is iterable or False otherwise.

You can name the function as isiterable() :

Anytime you want to check if an object is iterable, you just call the function as follows:

The isiterable() function will make checking for iterable objects convenient and easy. 😉

Conclusion

This article has shown different ways to check if an object is iterable in Python.

You can use the iter() function and a try-except block, or isinstance() and an if-else block.

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

I hope this article was helpful. See you again in other articles! 👋

Take your skills to the next level ⚡️

I’m sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I’ll send new stuff straight into your inbox!

About

Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.

Type the keyword below and hit enter

Источник

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.

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.

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

Further reading:

Get class name in Python
NoneType in Python

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__ .

Источник

Оцените статью