Python3-Generator Genarator

Source: Internet
Author: User
Tags function definition

in Python, this side loop computes the mechanism, called the generator: Generator. 

The generator holds the algorithm, each time it calls next (), calculates the value of the next element,
throws a stopiteration exception until the last element is calculated and no more elements are thrown
of course, this constant call to next () is so perverted that the correct approach is to use a for loop because the generator is also an iterative object.
So, after we've created a generator, basically never call next (),
instead, it iterates through the for loop and does not need to care about the stopiteration exception.

How to create a generator:
1, as long as a list is generated when the [] change to ()
2, another way to define generator. If a function definition contains the yield keyword, then the function is no longer a normal function, but a generator


when calling generator with a for loop, it is found that the return value of generator Return statement is not available. If you want to get the return value, you must catch the Stopiteration error, and the return value is contained in the value of Stopiteration
While True:
Try:
x = Next (g)
print ("value:%d"%x)
except Stopiteration as E:
print ("Generator return value:%s"%e.value)
Break

The generator is a function that remembers the position of the last time it was returned in the body of the function. A second (or nth) call to the generator function jumps to the middle of the function, and all local variables that were last called remain unchanged.
The generator not only "remembers" its data state; the generator also "remembers" its location in flow control constructs (in imperative programming, this construct is not just a data value).

features of the generator:
1. Save Memory
2, the iteration to the next call, the parameters used are the first time to leave,
That is, the parameters of all function calls are preserved the first time they are called, not the newly created

Python3-Generator Genarator

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.