Python is iterable function

Как проверить является ли объект итерируемым в Python

Python не имеет встроенного метода isiterable() для проверки, является ли объект итерируемым или нет. Но есть несколько способов, с помощью которых можно определить, является ли объект итерируемым. Некоторые из подходов являются дорогостоящими операциями, а некоторые иногда не осуществимы в использовании.

Является ли объект итерируемым

Чтобы проверить, является ли объект итерируемым в Python, используйте метод iter(). Python iter() — это встроенная функция, которая возвращает итератор для данного объекта.

Метод iter() — это наиболее точный способ проверить, является ли объект итерируемым, и обработать исключение TypeError, если это не так.

Синтаксис функции iter() следующий.

Пример

Давайте назначим целое число переменной данных и проверим итерацию.

Проверка с помощью коллекций в Python

Чтобы проверить, является ли объект итерируемым в Python, используйте абстрактный класс Iterable модуля collections. Модуль collections предоставляет некоторые абстрактные базовые классы, которые позволяют запрашивать классы или экземпляры, предоставляют ли они определенную функциональность.

Python isinstance() — это встроенный метод, который возвращает True, если указанный объект имеет указанный тип. В противном случае возвращается False. Мы будем использовать абстрактный класс Iterable и метод isinstance(), чтобы проверить, является ли объект итерируемым или нет в Python.

Чтобы работать с классом Iterable, нам нужно сначала его импортировать.

Читайте также:  Php mysqli get result array

Источник

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

Источник

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