Python check is iterator

How to check if an object is iterable in Python

An iterable is an object which can be traversed. Data structures like array, string, and tuples are iterables.

In certain cases, e.g., when dealing with custom data types, we may not know whether an object is iterable, but for this there should be some kind of mechanism through which a user can estimate its iterable status.

In this article, we will see how we can identify if an object is iterable using three techniques.

1. Iterating over the object¶

This is the simplest way to check if an object is iterable.

This style of programming is called duck typing («If it looks like a duck and quacks like a duck, it must be a duck.»).

Читайте также:  Http request types php

2. Using iter() ¶

If an object is iterable, it will not throw an error when used with iter() . It checks if the passed object has __iter__() or __getitem__() method available, which are methods that iterables possess.

3. Using collection.abc.Iterable¶

The collection library houses specialized container datatypes and abstract base classes to test if a class provides particular interfaces. Coupled with built-in isinstance() method we can get a boolean response. This technique does not work with classes that implement __getitem__() dunder method.

FREE VS Code / PyCharm Extensions I Use

✅ Write cleaner code with Sourcery, instant refactoring suggestions: Link*

PySaaS: The Pure Python SaaS Starter Kit

🚀 Build a software business faster with pure Python: Link*

* These are affiliate link. By clicking on it you will not have any additional costs. Instead, you will support my project. Thank you! 🙏

Источник

Python check is iterator

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.

Источник

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

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

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

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

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

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

Пример

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

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

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

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

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

Источник

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

Источник

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