Mostly like a normal function
Use yield rather than return
maintains state
A generator is like a normal function, but instead of a return statement, it has a field statement.
Each time the yield statement is reached, it provides the next value in the sequence.
When there are no more values, the ruction calls return, and the loop stops.
A generator function maintains state between calls, unlike a normal function.
>>> def numbers():
... a = 0
... for i in range(3):
... yield a
... a = a + 1
... for i in range(3):
... yield a
... a = a - 1
... yield 100
... yield 200
... yield 300
>>>
>>> for num in numbers():
... num
...
0
1
2
3
2
1
100
200
300
>>>
>>> def next_prime(limit):
... flags = set()
... for i in range(2, limit):
... if i in flags:
... continue
... for j in range(2 * i, limit + 1, i):
... flags.add(j)
... yield i
>>> for prime in next_prime(200):
... print(prime, end=' ')
...
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199
>>> def trimmed(file_name):
... with open(file_name) as file_in:
... for line in file_in:
... if line.endswith("\n"):
... line = line.rstrip('\nr')
... yield line
...
>>> for trimmedline in trimmed("mary.txt"):
... print(trimmedline)
...
Mary had a little lamb,
Little lamb, little lamb,
Mary had a little lamb
Whose fleece was white as snow.
And everywhere that Mary went,
Mary went, Mary went,
Everywhere that Mary went
The lamb was sure to go.