# This is a learning note for the Liaoche teacher Python tutorial
1 , overview
We have learned list, tuple, dict, set, str , Span style= "Font-family:simsun;background:lime;background:lime" >generator, generator function These can be used Span style= "Font-family:simsun;background:yellow;background:yellow" >for loop is an iterative ( iterable ) Object
But only generator and generator functions, which can be called by the next () function .
The Iterable object, which can be called by the next function, is called an iterator (Iterator)
1.1 , iterable to the Iterator the Transformation
Although iterable is not necessarily Iterator. But we can use the ITER () function to convert
L ist , Dict , Str wait iterable can use iter () function becomes Iterator :
# for Loop traversal list
For x in [1, 2, 3, 4, 5]:
Pass
# Convert to Generator traversal
It=iter ([1,2,3,4,5]) # define generator object it
While True:
Try
X=next (IT)
Except stopiteration:
Break
1.2 , why iterable is not necessarily Iterator
Why list, dict, str and other data types are not iterator it?
Because the Python iterator object represents a data stream , the iterator object can be called by the next () function and continuously return to the next data until the Stopiteration error is thrown when there is no data. This data stream can be seen as an ordered sequence, but we cannot know the length of the sequence in advance, we can only continue to calculate the next data on demand with the next () function, so the calculation of iterator is inert , It is calculated only if you need to return the next data.
Iterator 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.
1.3 , Summary
generally available for for the objects that are looped are iterable type;
generally available for Next () the objects of the function are Iterator types, which represent a sequence of lazy computations;
-
collection data type such as Dict , STR iterable but not iterator iter () function to get a iterator object.
Python of the for A loop is essentially a continuous call Next () function Implementation of the
Python Learning note __3.5 iterator