Python in generators and iterators

Source: Internet
Author: User
Tags generator

List-Generated

List generation is a method used within Python to create a list that is formatted like this:

 for  in range ()print(L)

Results are obtained at this time: [0, 8, 16, 24, 32, 40, 48, 56, 64, 72]. As we can see, with the list generation, a code can be replaced by a function loop, relatively concise.

Generator

With list generation, we can create a list directly. However, with memory limitations, the list capacity is certainly limited. Also, creating a list of 1 million elements takes up a lot of storage space, and if we just need to access the first few elements, the vast majority of the space behind it is wasted.

So, if the list element can be calculated according to an algorithm, can we continue to calculate the subsequent elements in the process of the loop? This eliminates the need to create a complete list, which saves a lot of space. In Python, this side loop computes the mechanism, called the generator: Generator.

As in the example above, we just need to change [] to () and create a generator at this point.

 for  in range ()print(L)

The result of the output is: <generator object <genexpr> at 0x00000138c692a7d8>. If you need to print the value of the generator (iterator), you need to use the next () function.

In addition, in addition to the methods described above to create generators, we can also use the keyword yield when defining a function. When the function definition contains yield, then this function is a generator (iterator).

Python in generators and iterators

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.