Python generator
is a special kind of functions that return iterables. It usually combined with yield
.
>>> def istwo(p): ... for i in p: ... if (i%2 == 0): ... print("i is: ",i) ... yield i ... >>> x = range(1,20) >>> for i in istwo(x): print(i)
i is: 2 2 i is: 4 4 i is: 6 6 i is: 8 8The function istwo(p) is a generator. It generate an iterable that can be used in the for loop. When the generator is called in the for loop, it return a value, and save the position of the iterator. In above example, istwo(x) will generate iterable [2,4,6,8], when it is call first time, it return 2, and next time it starts from 2 and return 4 .... Let's write above sample in the following style:
def istwo(): print("begin:") yield 2 print("After 2:") yield 4 print("After 4:") yield 6 print("After 6:") yield 8 print("After 8:") for i in istwo(): print(i)
begin: 2 After 2: 4 After 4: 6 After 6: 8 After 8:In the for loop, first cycle run all lines till "yield 2", second cycle starts after "yield 2", and execute all lines till temporially stop at line "yield 4" ..., till the for loop finished.