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