This is my piece of code with two generators defined:
one_line_gen = (x for x in range(3))
def three_line_gen():
yield 0
yield 1
yield 2
Why? I thought any generator can be used only once.
Because every call to three_line_gen() creates a new generator.
Otherwise, you're correct that generators only run forward until exhausted.
Can generator be used more than once?
Yes, it is possible if the results are buffered outside the generator. One easy way is to use itertools.tee():
>>> from itertools import tee
>>> def three_line_gen():
yield 0
yield 1
yield 2
>>> t1, t2 = tee(three_line_gen())
>>> next(t1)
0
>>> next(t2)
0
>>> list(t1)
[1, 2]
>>> list(t2)
[1, 2]