# Iterator: amazing behavior

I came across the following example:

  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]
0
0

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]
0
1

edit retag close merge delete

Sort by ยป oldest newest most voted

The 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)
19

more

## Stats

Seen: 392 times

Last updated: Mar 03 '19