About my understanding of iteratable objects, iterators, generators

Iteratable object:

An object that can return an iterator can be called an iteratable object. In essence, with__ iter__ Method is an iteratable object. In python, we can judge whether an object is an iteratable object through isinstance(). Common iteratable objects are: list, set, dict, tuple, str.
In [1]: from collections import Iterable

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

In [3]: isinstance(set(),Iterable)
Out[3]: True

In [4]: isinstance(dict(),Iterable)
Out[4]: True

In [5]: isinstance((1,),Iterable)
Out[5]: True

In [6]: isinstance('hello world',Iterable)
Out[6]: True
__ iter__ Method: you can return an iterator
Customize simple iteratable objects
In [7]: class A(object):
   ...:     def __iter__(self):
   ...:         """Returns an iterator"""
   ...:         pass  

In [8]: a = A()
In [9]: isinstance(a,Iterable)
Out[9]: True

Iterator:

When the next () method is called, the object that returns the next value in the iteratable object can be called an iterator. In essence, realize_ iter__ Methods and__ next_ The object of the (next()) method in python2 is the iterator (from here we can see that the iterator itself is also an iteratable object)
In [10]: from collections import Iterator

In [11]: isinstance([], Iterator)
Out[11]: False

In [12]: isinstance(iter([]), Iterator)
Out[12]: True

In [13]: isinstance(iter("abc"), Iterator)
Out[13]: True
__ iter__ Method: you can return the iterator itself
__ next__ Method: you can return the next value in the iteratable object. If there is no next value in the iteratable object, a StopIteration exception will be thrown.
In python, we can use the isinstance() method to determine whether an object is an iterator object.
Customize simple iterators
In [14]: class B(object):
    ...: 
    ...:     def __next__(self):
    ...:        """"" "record current iteration position" ""
    ...:         pass
    ...: 
    ...:     def __iter__(self):
    ...:        """"" "return iterator itself" ""
    ...:         pass
    ...:     

In [15]: b = B()

In [16]: from collections import Iterator

In [17]: isinstance(b,Iterable)
Out[17]: True

Generator

A special type of function that generates one value at a time can be called a generator. In short, during the execution of the function, the yield statement will return the value you need to the place where the generator is called, and then exit the function. The next time the generator function is called, it will be executed from the place where it was interrupted last time, and all variable parameters in the generator will be saved for next use.
When we implement an iterator ourselves, the current iterated state needs to be recorded by ourselves, and then the next data can be generated according to the current state. The generator can record the current state through the yield statement, that is, the generator is a special kind of iterator.
Because the generator is a special iterator, the generator can be used through the next() function, for loop, list() and other methods
tips: in Python 3, the object returned by the range() method is a generator object, while in Python 2, the traversal result is returned
Write Fibonacci sequence using generator
In [18]: def fib(n):
   ....:     current = 0
   ....:     num1, num2 = 0, 1
   ....:     while current < n:
   ....:         num = num1
   ....:         num1, num2 = num2, num1+num2
   ....:         current += 1
   ....:         yield num
   ....:     return 'None'
Yield statement: when the python interpreter executes to the yield line, it will stop and return the variables behind yield. When it calls to activate yield again (call the next() method, etc.), it will continue to execute the code behind yield (return value can be added after return in python 3, return in python 2 can only exit the generator, and return value cannot be added later)

Summary:

1. An iteratable object is an object that can be iterated. It has iter method. Calling iter method can return an iterator
2. Iterator is a special iteratable object, which can record the object of the current access location. It has the next method. When calling the next (next in Python 2) method through next(), it will return the value of the next location. An iterator is a special iteratable object that returns itself when the iter method is called.
3. The generator is a special iterator. It automatically records the state of the current iteration. When we call the next() method, it will help us continue from the last stop

Keywords: Python

Added by ndorfnz on Sun, 20 Feb 2022 02:59:36 +0200