These objects, which can be directly applied to for
the loop, are called iterative 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
An object that can be called by next()
a function and continually returns the next value is called an iterator: Iterator
.
You can use to isinstance()
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,, list
dict
str
Though Iterable
they are, they are not Iterator
.
Turn list
, dict
and str
wait for the Iterable
Iterator
function to be used iter()
:
>>> isinstance(iter([]), Iterator)True>>> isinstance(iter(‘abc‘), Iterator)True
You may ask, why, list
dict
, str
etc. data types are not Iterator
?
This is because the Python Iterator
object represents a data stream, and the iterator object can be next()
called by the function and will return the next data continuously until there is no data to throw an StopIteration
error. You can think of this data stream as an ordered sequence, but we can't know the length of the sequence in advance, only by continuously using the next()
function to calculate the next data on demand, so Iterator
the calculation is lazy, and it will only be calculated when the next data needs to be returned.
Iterator
It can even represent an infinitely large stream of data, such as the whole natural number. Using list is never possible to store all natural numbers.
Python Practical note (11) Advanced Features--iterators