Learn more about the yield and generator of Python

Source: Internet
Author: User
Objective
There is no use of things, there is no deep understanding of things difficult to say that they will, and be asked by others inevitably flawed. Although the previous contact with the concept of Python, but just a glance, the two days of a conversation, others asked the association, suddenly speechless, dead and alive to think of things that have been seen, then suddenly thought of yield, but too late, can only say the concept of unclear, So this article first strands Python generator and yield keyword.

What is a generator
1, the generator is a special program, can be used as a control loop iterative behavior
2, the generator is similar to the return value of a function of an array, this function can receive parameters, can be called, but, unlike the general function will return an array containing all the values at once, the generator produces only one value at a time, so that the amount of internal coarse consumption is greatly reduced, and allowing the calling function to quickly start processing the first few return values. As a result, the generator looks like a function but behaves like an iterator.
The builder in Python
Python provides two basic ways to do this.

1), generator function: Also defined with Def, using the keyword yield to return one result at a time, block, start again
2), Generator expression: Returns an object that produces the result only when needed
Explained in detail below.

1. Generator function
Why is it called a generator function? Because he built a numerical queue over time. The general function returns a value after execution and exits, but the generator function automatically hangs and then picks up and resumes execution, and he uses the yield keyword to close the function, returning a value to the caller, and keeping the current enough state so that the function can continue to execute. The generator and iteration protocol are closely related, and an iterative object has a __next () __ Member method that either returns the next item of the iteration or causes an unexpected end iteration.
To support iterative protocols, functions that have yield statements are compiled into generators, which are called to return a generator object, and the returned object supports an iterative interface, that is, the member Method __next () __ continues execution from the break.
Look at the following example:

# Codesdef Create_counter (n): print "Create Counter" while True:  yield n  print ' increment n '  n + = 1cnt = creat E_counter (2) Print Cntprint next (CNT) print next (CNT) # output
 
  
   
  create counter2increment n3
 
  

Analyze This example:

    • A keyword yield appears in the Create_counter function, indicating that the function produces only one result value at a time, which returns a generator (as can be seen from the first line of output) to produce a continuous n value
    • When creating an instance of a generator, you only need to call it like a normal function, but this call does not execute the function, which can be seen through the output
    • The next () function takes the generator object as its own parameter, and at the first call, he executes the create_counter () function to the yield statement, returning the resulting value 2.
    • We call the next () function repeatedly, and each time he executes from the last place where it was suspended until he encounters the yield keyword again

For a deeper understanding, let's give another example.

#codingdef Cube (n): For I in range (n):  yield i * * 3for i in Cube (5): Print i#output0182764

So from the point of view of the function we can take the yield analogy to return, but the function is really quite different, in the For loop, will automatically follow the iteration rules, each call to the next () function, so the above results are not difficult to understand.

2. Generator expression
The builder expression comes from the combination of iteration and list resolution, and the concept and usage of list parsing can be found in my previous blog, which is similar to the generator expression and list resolution, but is enclosed in angle brackets instead of square brackets. The following code:

>>> # List resolution build list >>> [x * * 3 for X in range (5)][0, 1, 8, 64]>>> >>> # Builder Expression >>  > (x * * 3 for X in range (5))
 
  at
  
   
   0x000000000315f678>>>> # Conversion between the two >>> list (x * * 3 for X in range (5)) [0, 1, 8, +, +]
 
  

In terms of operations, the generator table can be very inconvenient if a large number of next () functions are used, and the for loop will automatically go to the next function, so it may be used as follows:

Comparison of the two
An iteration can be written either as a generator function or a generates builder expression that supports both automatic and manual iterations. And these generators only support one active iteration, which means that the generator's iterator is the generator itself.

Summarize
Think of junior high school when the teacher often said, the eye view times, rather than manual again.

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.