Python has a command called yield to make it easy to create a generator. I didn't really understand the behavior, so I'll leave a note below.
test.py
def yield_test():
list0to4 = [0, 1, 2, 3, 4]
for i in list0to4:
yield i
for j in yield_test()
print j
If you run the above code, the output will be as follows.
0
1
2
3
4
All the elements of [0, 1, 2, 3, 4] can be read in order.
Now consider the case of using another generator in combination.
test.py
def yield_test1():
list0to4 = [0, 1, 2, 3, 4]
for i in list0to4:
yield i
def yield_test2():
list0to2 = [0, 1, 2]
for i in list0to2:
yield i
iter0to2 = yield_test2()
for j in yield_test1()
print j + iter0to2.next()
In this case, the output will be as follows.
0
2
4
yield_test2 has fewer elements than yield_test1, but there are no particular errors.
The generator raises an exception [StopIteration] when it goes to read the next without the next element. In the for statement etc., it seems that the loop is stopped by excluding this [Stop Iteration]. Therefore, in the above example, iter0to2.next () raises [StopIteration]. Even if the element remains on the yield_test1 () side, the for statement will be omitted.
When using a combination of generators, which one caused the loop to exit? Please note that it may be difficult to understand.
Recommended Posts