On the difference between list generation and generator in Python

Source: Internet
Author: User
List-generated syntax:

[X*x for X in range (0,10)]//list generation, here is the bracket//result [0, 1, 4, 9, +, +, +, $,, Bayi] (x*x for X in range (0,10))//generator, here is the parenthesis Results 
 
  at 
 
  
   0x7f0b072e6140>
 
 

The difference between the two is obvious:
One directly returns the result list of the expression, and the other is an object that contains a computed reference to the result of the expression, which can be directly output through a loop

g = (x*x for x in range (0,10)) for N in G:  print N

Results

0149162536496481

When the number of results of an expression is small, the use of list generation is OK, once the order of magnitude is too large, then the list generation will occupy a lot of memory,
Instead of immediately writing the results to memory, the generator is a method of saving, which is used to obtain the value of the corresponding position by constant acquisition, so the memory occupied is only the saving of the calculated object.

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