1.
Generator definition
In Python, the mechanism of computing while looping is called a generator: generator.
2. Why a
generator
All the data in the list is in memory. If there is a large amount of data, it will consume a lot of memory.
For example: only need to access the first few elements, then the space occupied by most of the latter elements is wasted.
If the list elements are calculated according to a certain algorithm, then we can continuously calculate the subsequent elements in the process of the loop, so that it is not necessary to create a complete list, thereby saving a lot of space.
In a word: I want to get huge data, and I want it to take up less space, then use a generator!
3. How to create a generator
The first method is very simple, as long as the [] of a list generator is changed to (), a generator is created:
>>> L = [x * x for x in range(10)]
>>> L
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> g = (x * x for x in range(10))
>>> g
<generator object <genexpr> at 0x1022ef630>
The difference between creating L and g is only the outermost [] and (), L is a list, and g is a generator.
Method 2: If a function contains the yield keyword, then the function is no longer an ordinary function, but a generator. Calling a function creates a generator object.