Thoroughly Understand The Python Generator

Source: Internet
Author: User
Keywords python generator understanding python generator
1. Generator definition
In Python, the mechanism of computing while looping is called a generator: generator.

 

2. Why a generator
All the data in the list is in memory. If there is a large amount of data, it will consume a lot of memory.

For example: only need to access the first few elements, then the space occupied by most of the latter elements is wasted.

If the list elements are calculated according to a certain algorithm, then we can continuously calculate the subsequent elements in the process of the loop, so that it is not necessary to create a complete list, thereby saving a lot of space.

In a word: I want to get huge data, and I want it to take up less space, then use a generator!

 

3. How to create a generator
The first method is very simple, as long as the [] of a list generator is changed to (), a generator is created:


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

 The difference between creating L and g is only the outermost [] and (), L is a list, and g is a generator.

 
Method 2: If a function contains the yield keyword, then the function is no longer an ordinary function, but a generator. Calling a function creates a generator object.
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.