Python generator, python

Source: Internet
Author: User

Python generator, python

Here I want to see a line of code

This is a list generator. What if the number we give is not range (10) But range (100000000000000. As we all know, generating a list requires memory usage. If the number of ranges is large enough, it will occupy a lot of memory and waste a lot of memory.

So we will introduce a new term "generator". So what is a generator?

We can understand that data is generated only when it is called;

For example:

B = (I * 2 for I in range (20000000000) This is a simple generator. Note that here is (). Think about it: In comparison, the former saves more memory space and is faster, and its memory address is not ready yet. Instead, it only prepares algorithms. When called, it will generate a direct result based on the algorithm. The disadvantage is that list slicing is not supported. When extracting the expected number, you need to use _ next _ () to indicate next () in python2. For example:

 

You need to call it in the form of B. _ next _ ().

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.