ASKSAGE: Sage Q&A Forum - Individual question feedhttp://ask.sagemath.org/questions/Q&A Forum for SageenCopyright Sage, 2010. Some rights reserved under creative commons license.Sun, 03 Mar 2019 02:40:48 -0600Iterator: amazing behaviorhttp://ask.sagemath.org/question/45609/iterator-amazing-behavior/ I came across the following [example:](https://treyhunner.com/2018/06/how-to-make-an-iterator-in-python/)
def count(start=0):
num = start
while True:
yield num
num += 1
When I try to apply it (Sage 8.6), the result is different than I expected:
print [count().next() for i in range(18)]
print next(count())
print next(count())
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] <br>
0 <br>
0 <br>
Can someone please elucidate why the output is not equal to:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17] <br>
0 <br>
1 <br>
Sun, 03 Mar 2019 02:03:52 -0600http://ask.sagemath.org/question/45609/iterator-amazing-behavior/Answer by rburing for <p>I came across the following <a href="https://treyhunner.com/2018/06/how-to-make-an-iterator-in-python/">example:</a></p>
<pre><code> def count(start=0):
num = start
while True:
yield num
num += 1
</code></pre>
<p>When I try to apply it (Sage 8.6), the result is different than I expected:</p>
<pre><code>print [count().next() for i in range(18)]
print next(count())
print next(count())
</code></pre>
<p>[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] <br>
0 <br>
0 <br></p>
<p>Can someone please elucidate why the output is not equal to:</p>
<p>[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17] <br>
0 <br>
1 <br></p>
http://ask.sagemath.org/question/45609/iterator-amazing-behavior/?answer=45610#post-id-45610The generator is defined correctly, but you're not using it in the right way.
Expression `count()` creates a *new instance* of the generator; so the first time you call `next()` it will give zero.
Instead, you should create it once, and then call `next()` several times on the resulting object, e.g.:
sage: mycount = count()
sage: [mycount.next() for i in range(18)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]
sage: mycount = count()
sage: [next(mycount) for i in range(18)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]
sage: next(mycount)
18
sage: next(mycount)
19Sun, 03 Mar 2019 02:40:48 -0600http://ask.sagemath.org/question/45609/iterator-amazing-behavior/?answer=45610#post-id-45610