Python Learning-Generator generator

Source: Internet
Author: User
Tags function definition generator generator generator

Generator function: If the yield keyword appears in the function, then this function is the generator function, and yield is the function of generating a generator, and the generator function returns a generator.

A generator is created by implementing a generator:1, replacing the list's [] with ().

>>> L = [x * x for x in range(10)]>>> L[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]>>> g = (x * x for x in range(10))>>> g<generator object <genexpr> at 0x1022ef630>

Mode 2, through the yield keyword. If a function definition contains a yield keyword, then the function is no longer a normal function, but a generator.
The generator implements the __iter__ method and the next () method. The generator is an iterative object and an iterator. Can be used for a for loop.

There is a lot of overhead in building iterators in Python; You must use the __iter__() and __next__() method to implement a class that tracks the internal state and throws an exception when no value is returned StopIteration .

The Python builder is an easy way to create iterators.

1. Call the generator function and return a generator.

2. When invoking the next () method of the generator, the generator starts executing the generator function until it encounters yield and pauses execution (hangs), and the yield parameter is used as the return value of the next method.

3. After each call to the next method of the generator, the generator resumes execution of the generator function from the location where it was last paused until the yield is encountered again, and the yield parameter will be the return value of the next method.

Python Learning-Generator generator

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.