Python advanced tutorial loop object

  • 2020-04-02 14:02:56
  • OfStack

The main purpose of this lecture is to give you a basic idea of looping objects as you read Python programs.

Looping objects did not exist with the birth of Python, but it is growing rapidly, especially in the age of Python 3x, where looping objects are becoming the standard form of looping.

What is a loop object

A loop object is an object that contains a next() method (s) (s), in python 3x, whose purpose is to proceed to the next result, and then, after the sequence of results has ended, to raise a StopIteration error.

When a loop structure (such as for) calls a loop object, it calls the next() method every time it loops until a StopIteration appears and the for loop receives it, it knows that the loop has ended, and it stops calling next().

Suppose we have a file called test.txt:


1234
abcd
efg

Let's run the python command line:

>>>f = open('test.txt')
>>>f.next()
>>>f.next()
...

Keep typing f.next() until you get a StopIteration at the end

Open () actually returns a loop object that contains the next() method. The next() method returns a new line each time, with StopIteration at the end of the file. So, we're kind of doing a manual loop.

If done automatically, it is:


for line in open('test.txt'):
    print line

Here, the for structure automatically calls the next() method, assigning the method's return value to line. The loop ends when a StopIteration occurs.

The advantage of using loop objects over sequences is that you don't have to generate the elements you want to use before the loop has even started. The elements used can be generated step by step during the loop. In this way, space is saved, efficiency is improved and programming is more flexible.

The iterator

Technically, there is an intermediate layer between the loop object and the call to the for loop, which translates the loop object into an iterator. This conversion is achieved by using the iter() function. But on a logical level, this layer can often be ignored, so the loop object and iterator often refer to each other.

The generator

The main purpose of the generator is to form a user-defined loop object.

The generator is written similarly to the function definition, except that it is changed to yield at return. You can have multiple yields in a generator. When the generator encounters a yield, it pauses the generator and returns a value after the yield. When the generator is called again, it continues from where it was paused until the next yield. The generator itself constitutes a loop, 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, and if used as a loop, it loops three times.

for i in gen():
    print i

Consider the following generator:


def gen():
    for i in range(4):
        yield i

It can also be written as Generator Expression:

G = (x for x in range(4))

Generator expressions are an easy way to write a generator. Further information is available.

Table is

List comprehension is a method of quickly generating tables. Its grammar is simple and practical.

Suppose we generate table L:


L = []
for x in range(10):
    L.append(x**2)

The above results in table L, but there is actually a quick way to write it, which is how the table is derived:

L = [x**2 for x in range(10)]

This is similar to a generator expression, except with brackets.

(the mechanism for table derivation is actually to make use of circular objects, which you can refer to if you are interested.)

What results from practicing the table derivation below?


xl = [1,3,5]
yl = [9,12,13]
L  = [ x**2 for (x,y) in zip(xl,yl) if y > 10]

conclusion

Circular object
The generator
Table is


Related articles: