The Advantages of Python Generator

Source: Internet
Author: User
Keywords python generator python generator advantage
I first want to understand the advantages of learning new things, and then judge whether it is necessary to continue to play it. So first introduce the advantages of the generator!

Advantages of python generator:

(1) Delay calculation and return one result at a time. The generator does not generate all the results at once, but calculates while looping, which is a very useful advantage for processing large amounts of data. Because in the actual application of programming, the amount of memory occupied is an issue that engineers must consider.

(2) Effectively improve code readability. After using the generator, there are fewer lines of code. (The following example will illustrate)

After talking about the advantages of generators, let's introduce how python represents generators.

There are two representations of generators in Python: (1) generator function (2) generator expression

(1) Generator function

The generator function is the same as the ordinary function definition in Python, which is defined using the def keyword. The difference is that the generator uses the yield statement instead of the return statement to return the result. When the generator function is executed, each time the yield statement is executed, the result is returned once, and then the function is suspended. When the generator function is executed again, the execution continues from the yield statement that was returned last time. (Delay calculation characteristics)

Examples illustrate:

Define common functions and generator functions to find the square of 0~10

Definition and call of ordinary functions:

def getSquare_l(maxVal):

Square_list = []

For i in range(maxVal+1):

Square_list.append(i*i)

Return square_list

square_list = getSquare_l(10)

square_list: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Definition and call of generator function:

def getSquare_g(maxVal):

For i in range(maxVal+1):

Yield i*i

square_generator = getSquare_g(10)

square_generator: <generator object getSquare_g at 0x109b7e308>

You can see that calling the generator function returns a generator object. If you want to extract the value in the generator, you can use the next method to extract until a StopIteration exception occurs.

next(square_generator): 0

next(square_generator): 1

...

next(square_generator): 100

next(square_generator): StopIteration

But this is too much trouble, we can also use the for loop to extract the generator object:

for i in square_generator:

Print(i)

By comparing the generator function with the ordinary function, you can see that the generator function requires less code and improves the readability of the code.

It needs to be bold here. The generator has many benefits, but one thing to note is that the generator can only traverse once. Because after traversing the generator object, there is no record in the generator (I think this is another reason why the generator saves memory).

(2) Generator expression

When it comes to generator expressions, you have to mention list comprehension. I believe everyone has heard of list generation. This is also a very powerful feature in Python, you can generate a list with very little code. Xiaobian I only learned Python for 3 weeks in the algorithm class. This feature was regarded as the focus by the teacher. During the mid-term and final exams, I took this knowledge point.

Also find the square of 0~10

List generation formula: [i*i for i in range(11)] Result: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

The so-called generator expression is to replace [] of the list generator with ().

Generator expression: (i*i for i in range(11)). Similarly, the next method or for loop method is required for extraction.

So easy! Replacing [] with () will save a lot of memory space when performing large data operations. Let's applaud for python's generator
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.