python generator

Keywords: Python

1, Generator definition

By generating expressions from lists, we can create a list directly. However, due to the memory limitation, the list capacity must be limited. So, if list elements can be calculated according to some algorithm, can we continuously calculate the following elements in the process of circulation? This saves a lot of space by eliminating the need to create a complete list. In Python, the mechanism of calculating while looping is called generator.

1 >>> l = [x * x for x in range(10)]
2 >>> l
3 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
4 >>> g = (x * x for x in range(10))
5 >>> g
6 <generator object <genexpr> at 0x1013e0780>

2, Expression builder

The only difference between creating L and g is that the outermost [] and (), l is a list, and g is a generator. You can print every element of L directly, and you need to use the next() function to print every element of g.

 1 >>> g = (x * x for x in range(10))
 2 >>> g
 3 <generator object <genexpr> at 0x1013e0780>
 4 >>> next(g)
 5 0
 6 >>> next(g)
 7 1
 8 >>> next(g)
 9 4
10 >>> next(g)
11 9
12 >>> next(g)
13 16
14 >>> next(g)
15 25
16 >>> next(g)
17 36
18 >>> next(g)
19 49
20 >>> next(g)
21 64
22 >>> next(g)
23 81
24 >>> next(g)
25 Traceback (most recent call last):
26   File "<stdin>", line 1, in <module>
27 StopIteration

The generator saves the algorithm. Every time next(g) is called, the value of the next element of G is calculated. Until the last element is calculated, if there are no more elements, an error of StopIteration is thrown.

 1 >>> g = (x * x for x in range(10))
 2 >>> for n in g:
 3 ...     print(n)
 4 ... 
 5 0
 6 1
 7 4
 8 9
 9 16
10 25
11 36
12 49
13 64
14 81

First, the generator is an iterative object, so you can use the for in loop to traverse. The essence of this traversal is to call the next() function inside the for in loop to get each element, catch the StopIteration exception and end the traversal.

3, Function generator

Fiboracci series can't be written in tabular form, but it's easy to print out with functions.

 1 >>> def fib(max):
 2 ...     n, a, b = 0, 0, 1
 3 ...     while n < max:
 4 ...         yield b
 5 ...         a, b = b, a + b
 6 ...         n += 1
 7 ...     raise StopIteration('done')
 8 ... 
 9 >>> fib(6)
10 <generator object fib at 0x1013e0780>
11 >>> for i in fib(6):
12 ...     print(i)
13 ... 
14 1
15 1
16 2
17 3
18 5
19 8
20 >>> g = fib(6)
21 >>> while True:
22 ...     try:
23 ...         next(g)
24 ...     except StopIteration as e:
25 ...         print(e.value)
26 ...         break
27 ... 
28 1
29 1
30 2
31 3
32 5
33 8
34 done

Posted by cirko on Thu, 14 May 2020 08:39:56 -0700