How to pass values to a generator in a for loop?
<p>I know that you can use <code>.send(value)</code> to send values to an generator.  I also know that you can iterate over a generator in a for loop.  Is it possible to pass values to a generator while iterating over it in a for loop?</p>

<p>What I'm trying to do is</p>

<pre><code>def example():
    previous = yield
    for i range(0,10):
        previous = yield previous*i

t = example()
for value in example"...pass in a value?...":
    "...do something with the result..."
</code></pre>

<p>You technically could, but the results would be confusing. eg:</p>

<pre><code>def example():
    previous = (yield)
    for i in range(1,10):
        received = (yield previous)
        if received is not None:
            previous = received*i


t = example()
for i, value in enumerate(t):
  t.send(i)
  print value
</code></pre>

<p>Outputs:</p>

<pre><code>None
0
2
8
18
</code></pre>

<p>Dave Beazley wrote an <a href="http://www.dabeaz.com/coroutines/Coroutines.pdf" rel="nofollow">amazing article</a> on coroutines (<strong>tldr;  don't mix generators and coroutines in the same function</strong>)</p>

python generator