Python iterator and python Generator
The objects that can directly act on the for loop are called iterable objects. The objects that can be called by the next () function and continuously return the next value are called iterator ); all iteratable objects can be converted to iterators through the built-in function iter. When the for loop is used, the program automatically calls the iterator object of the object to be processed, and then uses its next () method until it detects a stoplteration exception.
>>> L = [, 0] # This is a list
>>> I = iter (l) # The iteratable object is converted into an iterator;
>>> Next (I)
4
>>> Next (I)
5
>>> Next (I)
6
>>> Next (I)
7
>>> Next (I)
8
>>> Next (I)
9
>>> Next (I)
0
>>> Next (I)
Traceback (most recent call last ):
File "<stdin>", line 1, in <module>
StopIteration
Because the number in the list exceeds 0, a StopIteration exception is returned if the range is exceeded.
How can we determine in the production environment?
>>> L = [4, 5, 6]
>>> I = L. _ iter __()
>>> L. _ next __()
Traceback (most recent call last ):
File "<stdin>", line 1, in <module>
AttributeError: 'LIST' object has no attribute '_ next __'
>>> I. _ next __()
4
>>> From collections import Iterator, Iterable
>>> Isinstance (L, Iterable)
True
>>> Isinstance (L, Iterator)
False
>>> Isinstance (I, Iterable)
True
>>> Isinstance (I, Iterator)
True
>>> [X ** 2 for x in I]
[25, 36]