For loop can act directly on the type of data are the following:
A class is a collection of data types, such as a list, tuple, dict, set, str, etc.
One is the generator, comprising a generator and a generator function with a yield of
These can act directly on the object for circulation collectively referred to as iterables: Iterable
Can use the isinstance () determines whether an object to be Iterable objects
>>> 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
So here we talk about iterators
Iter implements a method is iterative object, the object is a method to achieve next iterator;
May be next () function call and return to the next target value continuously referred iterator: Iterator.
Can use the isinstance () determines whether an object is Iterator objects:
>>> from collections import Iterator
>>> isinstance((x for x in range(10)), Iterator)
True
>>> isinstance([], Iterator)
False
>>> isinstance({}, Iterator)
False
>>> isinstance('abc', Iterator)
False
Builder is Iterator
an object, but list
, dict
, str
though Iterable(可迭代对象)
, is not Iterator(迭代器)
.
The list
, dict
, str
etc. Iterable
becomeIterator
can use the iter()
function :
>>> isinstance(iter([]), Iterator)
True
>>> isinstance(iter('abc'), Iterator)
True
Why list
, dict
, str
and other data types are not Iterator
?
This is because Python is Iterator
an object representation of the data flow , Iterator objects can be next()
invoked continue to function and returns the next data until the absence of data thrown StopIteration
error. This data stream can be seen as an ordered sequence, but we can not know in advance the length of the sequence, can only continue through the next()
realization of next-demand computing a data function, so the Iterator
calculations are inert, only need to return the next data it will be calculated.
Iterator
Even represent an infinite stream of data, such as all natural numbers. The list is never stored using all natural numbers.