Python iterators & Generators

Source: Internet
Author: User
Tags for in range

Generator

    • With a list build, you can generate a list directly. However, the list capacity is limited by memory constraints. If you create a list that contains 1 million elements, you only need to access a few of them, and the space is wasted.
    • If a list element can be calculated according to an algorithm, the subsequent elements are continually extrapolated during the loop so that there is no need to create a complete list, thus saving 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: Changing a list-generated [] to () creates a generator
    • 1  for  in range,2 >>> L34 for in range (ten)) 5 >>> G
    • 1 #!/usr/bin/python2 #-*-coding:utf-8-*-3 4A = []5  forIinchRange (10):6A.append (i*2)7 8 Print(a)9 Ten  One Print("========== The above code is equivalent to the following sentence ==========") Ab = [i*2 forIinchRange (10)] - Print(b) -  the  - Print("============== More advanced wording ==============") -c = [Func (i) forIinchRange (10)] - Print(c)
      View Code

Python iterators & Generators

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.