Lazy Calculations for Python generators

Source: Internet
Author: User
Tags generator

Recently learned Python iterators and generators, the generator is a feature, is to use the data will be used to fetch! Look at the following code and think about it, and you'll understand what lazy computing is!

1 defAdd (S, x):2     returnS +x3 4 5 defGen ():6      forIinchRange (4):7         yieldI8 9 TenBase =Gen () One  forNinch[1, 10]:  ABase = (Add (i, N) forIinchbase) - Print(List (base))

Output: [20, 21, 22, 23] very puzzled, please look down

The key point of this problem is the following points:

1. Because the loop is doing is to generate data with the generator expression, and the generator has a lazy calculation characteristics, leading us to lead a road of no return, we are false illusion, in fact, it did not do anything, but simply walk on both sides of the process

2. The generator is waiting for the time to use (such as printing or next function to value, etc. ) will be calculated when the production, so wait until the last printing time to start the calculation

3. When the production data is started, the value of the two N of the loop has become 10.

4. The first cycle generator production number used to base or bound Gen take 0,1,2,3 processed (add function plus operation), the generator produced 10,11,12,13, and then base successfully occupy the generator

5. When the second loop is in the base value, base is no longer gen but the last loop rebinding base, so the value taken is 10,11,12,13 and then produced 20,21,22,23 by its own processing.

6. Do not think of the for-N in [1,10] as a for-N in range (1,10)

7. Maybe n becomes 10 very unexpected, but after understanding the inertia, it is understood that for the god of magic N is not in the 1 o'clock operation

8. It is important to clarify the binding relationship of base at a certain moment.

Hope this blog can help you! Thank you! Light Greetings!

Lazy Calculations for Python generators

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.