Python practical notes (11) advanced features - iterator

These objects that can act directly on forloops are collectively called iterable objects: Iterable.

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

>>> 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 

An object that can be called by next()a function and keeps returning the next value is called an iterator: Iterator.

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

>>> 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 Iteratorobjects, but list, dict, stralthough they are Iterable, but they are not Iterator.

Turn list, dict, stretc Iterableinto Iteratorusable iter()functions:

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

You might ask, why are list, dict, , stretc. data types not Iterator?

This is because Python Iteratorobjects represent a stream of data, and the Iterator object can be called by next()a function and keep returning the next data until StopIterationan error is thrown when there is no data. This data stream can be regarded as an ordered sequence, but we cannot know the length of the sequence in advance, and can only continuously next()calculate the next data on demand through the function, so Iteratorthe calculation is lazy, only when the next data needs to be returned it will only be calculated.

IteratorIt can even represent an infinite data stream, such as all natural numbers. And using list is never possible to store all natural numbers.

Guess you like

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