List-Generated
List generation is a method used within Python to create a list that is formatted like this:
for in range ()print(L)
Results are obtained at this time: [0, 8, 16, 24, 32, 40, 48, 56, 64, 72]. As we can see, with the list generation, a code can be replaced by a function loop, relatively concise.
Generator
With list generation, we can create a list directly. However, with memory limitations, the list capacity is certainly limited. Also, creating a list of 1 million elements takes up a lot of storage space, and if we just need to access the first few elements, the vast majority of the space behind it is wasted.
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.
As in the example above, we just need to change [] to () and create a generator at this point.
for in range ()print(L)
The result of the output is: <generator object <genexpr> at 0x00000138c692a7d8>. If you need to print the value of the generator (iterator), you need to use the next () function.
In addition, in addition to the methods described above to create generators, we can also use the keyword yield when defining a function. When the function definition contains yield, then this function is a generator (iterator).
Python in generators and iterators