Python builder, the use of yield

Source: Internet
Author: User

Generator: A function that contains the keyword of yield is a generator.

How the Generator works: When the function is called, the function stops when it runs to yield, the return value, and the next time the yield is executed, the local variable or the value of the variable is used. Equivalent to the function in yield is frozen, the next time continue to execute in the yield place.

Why use the generator.

The generator has the advantage of listing all the content at a time:

1. Save more storage space

2. Respond more quickly

3. Use more flexible

As an example:

Generator notation:

Def gen (n)    for I in range (n)            yiled i**2for i in Gen (5)    print (I, "", end= "")


0 1 4) 9 16

General wording:

def Square (n)      for inch range (n)]     return ls  for  in Square (5):    Print(i,"", end ="" )

0 1 4) 9 16

Python builder, the use of yield

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.