The main purpose of this lecture is to give you a basic concept of loop objects when reading Python programs.
The loop object does not exist with the birth of Python, but it has developed rapidly, especially in the era of Python 3x, where loop objects are becoming the standard form of loops.
What is a loop object
A loop object is an object that contains a next() method (__next__() method, in python 3x). The purpose of this method is to proceed to the next result, and after ending a series of results, a StopIteration error is cited.
When a loop structure (such as for) calls a loop object, it will call the next() method every time the loop is looped. Until StopIteration appears and the for loop is received, it will know that the loop has ended and stop calling next().
Suppose we have a file:
1234
abcd
efg
Let's run the python command line:
>>>f = open('')
>>>()
>>>()
...
Continue to enter() until StopIteration appears
The return of open() is actually a loop object containing the next() method. The next() method returns a new line every time, and StopIteration is cited when the file ends. In this way, we are equivalent to manually performing a loop.
If it is done automatically, it is:
for line in open(''):
print line
Here, the for structure automatically calls the next() method and assigns the return value of the method to the line. The loop knows that the StopIteration ends.
Compared to sequences, the advantage of using loop objects is that you don't need to generate the elements you want to use before the loop begins. The elements used can be generated successively during the loop. This saves space, improves efficiency, and makes programming more flexible.
Iterator
Technically speaking, there is an intermediate layer between the loop object and the for loop call, which is to convert the loop object into an iterator. This transformation is achieved by using the iter() function. But from a logical level, this layer can often be ignored, so loop objects and iterators often refer to each other.
Generator
The main purpose of a generator is to form a user-defined loop object.
The method of writing the generator is similar to the function definition, except that it changes to yield in the return place. There can be multiple yields in the generator. When the generator encounters a yield, the generator will be paused and the value after the yield will be returned. When the generator is called again, it will continue to run from the place where it was just paused until the next yield. The generator itself forms a circulator, each loop using a value returned by yield.
Here is a generator:
def gen():
a = 100
yield a
a = a*8
yield a
yield 1000
The generator has three yields in total, and if used as a circulator, it will perform three cycles.
for i in gen():
print i
Consider the following generator:
def gen():
for i in range(4):
yield i
It can be written as a generator expression:
G = (x for x in range(4))
Generator expressions are a simple way to write generators. Readers can read further.
Table Deduction
Table derivation (list comprehension) is a method to quickly generate tables. Its syntax is simple and very practical.
Suppose we generate table L:
L = []
for x in range(10):
(x**2)
The above produces table L, but there is actually a quick way to write it, that is, the method of table derivation:
L = [x**2 for x in range(10)]
This is similar to the generator expression, except that it uses brackets.
(The mechanism of table derivation is actually to use loop objects, you can check it if you are interested.)
Exercise What will the following table derivation generate?
xl = [1,3,5]
yl = [9,12,13]
L = [ x**2 for (x,y) in zip(xl,yl) if y > 10]
Summarize
Loop object
Generator
Table Deduction