python iterator

We already know that the data types that can be directly applied to the for loop are as follows:
one is a collection data type, such as list, tuple, dict, set, str, etc.;
the other is a generator, including generators and generators with yield function.
These objects that can act directly on the for loop are collectively called iterable objects: Iterable.

You can use isinstance() to determine whether an object is an Iterable object:

>>> from collections import Iterable
>>> isinstance([], Iterable)
True
>>> isinstance({}, Iterable)
True
>>> isinstance('abc', Iterable)
True
>>> isinstance((x for x in range(10)), Iterable)
True
>>> isinstance(100, Iterable)
False
The generator can not only act on the for loop, but also be continuously called by the next() function and return the next value, until the StopIteration error is finally thrown, indicating that the next value cannot be returned.
An object that can be called by the next() function and continuously returns the next value is called an iterator: Iterator.

You can use isinstance() to determine whether an object is an Iterator object:

>>> from collections import Iterator
>>> isinstance((x for x in range(10)), Iterator)
True
>>> isinstance([], Iterator)
False
>>> isinstance({}, Iterator)
False
>>> isinstance('abc', Iterator)
False
Generators are Iterator objects, but although list, dict, and str are Iterables, they are not Iterators.

To turn iterables such as list, dict, str, etc. into Iterators, you can use the iter() function:

>>> isinstance(iter([]), Iterator)
True
>>> isinstance(iter('abc'), Iterator)
True


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324730556&siteId=291194637