List of issues
The list Builder can create a table directly,
However, if there are 1 million elements in a table, the table takes up too much space,
And often we just need to access the first few elements, the vast majority of elements behind the space wasted.
Generator
If the list element can be calculated according to an algorithm, then we can continuously deduce the subsequent elements in the process of the loop. Instead of creating the entire list at the beginning.
This saves a lot of space.
The mechanism of this cycle over and over again is called the generator: Generator.
Create the generator generator.
The first method: simply report a list-generated [] change to () and wear a generator.
Create a list
for in range ()print L#[0, 1, 4, 9, +,,-
Creating generators
for in range (ten)) for in G: print n
The second method: use a function to implement. When a fission-generated for loop cannot be implemented, it can also be implemented with a function.
If a function definition contains the yield keyword, then the function is no longer a normal function, but a generator
def= 0, 0, 1 while n < m: yield b = b, A + B
= n + 1 return
In the generator, no arguments are allowed after return. Otherwise: syntaxerror: ' return ' with argument inside generator
Because in the generator, return causes stopiterationerror. The generic generator also does not return a value by this return.
How the Function Builder works:
The function definition contains the yield keyword so the function becomes the generator. During the generator execution, the yield is interrupted and the next time it continues from the point of break execution.
A generator defined by a function is generally not used next () to get the next return value. Instead, iterate directly with a for loop.
Python Generator Generator