Home >Backend Development >Python Tutorial >How to understand python iterable objects

How to understand python iterable objects

(*-*)浩
(*-*)浩Original
2019-08-02 10:49:3211518browse

What is an iterable object?

How to understand python iterable objects

The simple understanding is that objects that can be used for loops are iterable objects. For example: list, string, dict, tuple, generator, etc.

Have iterable characteristics. (Recommended learning: Python video tutorial)

Custom iterable object (essence)

At the syntax level, if an object implements __iter__ method, then this object is an iterable object

Judge whether it is an iterable object (Iterable)

通过调用Python内置的isinstance来判断是否是Iterable的实例

In [9]: isinstance([],Iterable)
Out[9]: True

In [10]: isinstance('',Iterable)
Out[10]: True

In [11]: isinstance({},Iterable)
Out[11]: True

In [12]: class MyList(object):
....:     def __init__(self):
....:         self.list = []
....:     def add(self,item):
....:         self.list.append(item)
....:         

In [13]: mylist = MyList()

In [14]: isinstance(mylist,Iterable)
Out[14]: False

Through the above example It can be seen that the objects of the built-in types dict, list, and str in Python are all iterable. We have customized a class MyList. Since this class does not implement the iter method, instances of this class are not iterable objects.

For more Python related technical articles, please visit the Python Tutorial column to learn!

The above is the detailed content of How to understand python iterable objects. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn