0

How can I write a function that would give me a new number in ascending order every time i call it?

For example, if I call it for the first time it returns "1", if I call again, it returns "2".

Wesley Murch
  • 101,186
  • 37
  • 194
  • 228
Maks
  • 237
  • 2
  • 4
  • 8
  • You may be interested in the accepted answer to this question: http://stackoverflow.com/questions/231767/the-python-yield-keyword-explained – asthasr Mar 29 '11 at 12:58
  • @syrion: that's "yield explained", probably for now just a mystical way for our friend here to get to his counter ;) – user237419 Mar 29 '11 at 13:02
  • Yeah, I also upvoted Sven's answer because it's more direct -- but the answer there explains *why* it works. :) – asthasr Mar 29 '11 at 13:03
  • @syrion: You wouldn't need `yield` to do this -- `counter = iter(xrange(0, 10**100))` would just work fine (the point here being that an explanation of *iterators* would be a more appropriate link than an explanation of *generators*). – Sven Marnach Mar 29 '11 at 13:08
  • Fair enough; I just tend to think of generators rather than iterators when I think of an infinite series of numbers. – asthasr Mar 29 '11 at 13:20

1 Answers1

7

How about itertools.count()?

counter = itertools.count()
print next(counter)
print next(counter)
print next(counter)

prints

0
1
2

If you want your counter to start from 1, use

counter = itertools.count(1)
Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
  • Trying to use itertools, i get "NameError: name 'itertools' is not defined" – Maks Mar 29 '11 at 13:25
  • @Maks: You have to `import itertools` at the beginning of the file. –  Mar 29 '11 at 13:29
  • Thank you. Also, i need those ascending numbers to be assigned to a string. As i udnerstand i cannot use "next" in that case. For example, "ouput = next(counter)" does not work – Maks Mar 29 '11 at 13:36
  • "Assigning to a string" does not seem to make any sense. And `output = next(counter)` will work fine. If you want to convert an `int` to a string, use `str()`. – Sven Marnach Mar 29 '11 at 13:42
  • I just get "Global name next is not defined" – Maks Mar 29 '11 at 13:55
  • @Maks: In versions of Python older than 2.6, you have to use `counter.next()` instead of `next(counter)`. – Sven Marnach Mar 29 '11 at 14:11