7. Generators¶
Lazy evaluation,
Memory effective
import collections, types
print(issubclass(types.GeneratorType, collections.Iterator))
True
Note
Generator is Iteratorem, but Iterator is not Generator !
7.1. Expression as generator¶
g = (n for n in range(20) if not n % 2) # just even !
for x in g:
print(x)
7.2. Function as generator¶
def simple_gen():
yield 5
yield 10
yield 15
s = simple_gen()
print(next(s))
print(next(s))
print(next(s))
5
10
15
# There are no elements to iterate over
print(next(s))
StopIteration:
def new_range(start=0, stop=None, step=1):
i = start
if stop is None:
while True:
yield i
i += step
else:
while i < stop:
yield i
i += step
g = new_range(2, 5)
print(next(g))
print(next(g))
2
3
Note
Generators are functions generating next values. When iterator then we should have next()
method.
7.3. Exercises part 1¶
Create generator, which is generating values which are 3 times greater than values from 0 to 20 ex. 0, 3, 6, 9, 12 …
7.4. Exercises part 2¶
Use file from list comprehension exercise list comprehension
Get this file using python
Hint
You can use library:
urllib
You can use default function
open
andreadline
Clean up the file,
Write generator converting date in text to date format,
Unfortunately, during logs creation we had our time set up badly. We need add 1 hour to the log hour
Hint
In package datetime
there is timedelta