Python Generator Generator

Source: Internet
Author: User

List of issues
The list Builder can create a table directly,
However, if there are 1 million elements in a table, the table takes up too much space,
And often we just need to access the first few elements, the vast majority of elements behind the space wasted.

Generator
If the list element can be calculated according to an algorithm, then we can continuously deduce the subsequent elements in the process of the loop. Instead of creating the entire list at the beginning.
This saves a lot of space.
The mechanism of this cycle over and over again is called the generator: Generator.


Create the generator generator.
The first method: simply report a list-generated [] change to () and wear a generator.
Create a list

 for  in range ()print  L#[0, 1, 4, 9, +,,-

Creating generators

 for  in range (ten)) for in G:  print n

The second method: use a function to implement. When a fission-generated for loop cannot be implemented, it can also be implemented with a function.
If a function definition contains the yield keyword, then the function is no longer a normal function, but a generator

def= 0, 0, 1 while n < m:    yield  b    = b, A + B
    = n + 1    return

In the generator, no arguments are allowed after return. Otherwise: syntaxerror: ' return ' with argument inside generator
Because in the generator, return causes stopiterationerror. The generic generator also does not return a value by this return.


How the Function Builder works:
The function definition contains the yield keyword so the function becomes the generator. During the generator execution, the yield is interrupted and the next time it continues from the point of break execution.
A generator defined by a function is generally not used next () to get the next return value. Instead, iterate directly with a for loop.

Python 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.