[Python Learning Article] [Liu Xuefeng] [1] Advanced Features--Create generator Method 1 A = (x for x in range (1,3))

Source: Internet
Author: User
Tags for in range

How to create a generator:

For x in range (1,10000000), Sir into a list [1........9999999] if we only want the next few elements, we will find a lot of wasted space. 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).

There are a number of ways to create a generator. The first method is simple, as long as a list of the generated formula is [] changed () to create a generator:

 for  in range () >>> 1, 4, 9, +, (+), +, +, Bayi]for in Range (Ten)>>> g<generator object <genexpr> at 0x104feab40>

How to get the generator element, you can calculate the value of the next element by next (), until the last element is calculated, and when there are no more elements, the Stopiteration error is thrown.

 for  in range (1,4))print  type (a)'generator'>> >> a.next ()1>>> a.next () 2>>> a.next ()3>>>  A.next () Traceback (most recent  ):'<stdin>'in <module>stopiteration>>>

Another way is: For loop

 for  in range (1,4)) for in a:print  x ... 123>>>

[Python Learning Article] [Liu Xuefeng] [1] Advanced Features--Create generator Method 1 A = (x for x in range (1,3))

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.