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.;
One class is the generator function generator
that includes generators and bands .yield
These objects that can act directly on for
loops are collectively called iterable objects: Iterable
.
You can use to isinstance()
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 can be next()
continuously called by the function and return the next value, until StopIteration
an error is thrown at the end, indicating that the next value cannot be returned.
* Objects that can be called by next()
a function and keep returning the next value are called iterators:Iterator
.
You can use to isinstance()
determine whether an object is an Iterator
object:
Generators are Iterator
objects, but list
, dict
, str
although they are Iterable
, but they are not Iterator
.
Turn list
, dict
, str
etc Iterable
into Iterator
usable iter()
functions:
You might ask, why are list
, dict
, , str
etc. data types not Iterator
?
This is because Python Iterator
objects represent a stream of data, and the Iterator object can be called by next()
a function and keep returning the next data until StopIteration
an 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 Iterator
the calculation is lazy, only when the next data needs to be returned it will only be calculated.
Iterator
It can even represent an infinite data stream, such as all natural numbers. And using list is never possible to store all natural numbers.
summary
Any for
object that can act on a loop is a Iterable
type;
All objects that can act on next()
functions are Iterator
types, and they represent a lazily computed sequence;
Collection data types such as list
, dict
, str
etc. are Iterable
but not Iterator
, but iter()
an object can be obtained through a function Iterator
.
Python's for
loops are essentially next()
implemented by constantly calling functions, for example:
for
x
in
[
1
,
2
,
3
,
4
,
5
]:
pass
# First get the Iterator object: it = iter([1, 2, 3, 4, 5]) # Loop: while True: try: # Get the next value: x = next(it) except StopIteration: # Exit the loop when StopIteration is encountered break