Ask Your Question
1

Iterator: amazing behavior

asked 2019-03-03 09:03:52 +0200

roland gravatar image

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 flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
4

answered 2019-03-03 09:40:48 +0200

rburing gravatar image

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
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

2 followers

Stats

Asked: 2019-03-03 09:03:52 +0200

Seen: 381 times

Last updated: Mar 03 '19