Generator question
Robert Kern
robert.kern at gmail.com
Sun Nov 26 04:29:36 EST 2006
Timothy Wu wrote:
> Hi,
>
> Using generator recursively is not doing what I expect:
>
> def test_gen(x):
> yield x
> x = x - 1
> if x != 0:
> test_gen(x)
The only thing that the last line does is *create* a new generator object. You
need to actually iterate over it and yield its values. E.g.
In [2]: def test_gen(x):
...: yield x
...: x -= 1
...: if x != 0:
...: for y in test_gen(x):
...: yield y
...:
...:
In [3]: list(test_gen(3))
Out[3]: [3, 2, 1]
--
Robert Kern
"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco
More information about the Python-list
mailing list